4

I am trying to bind two properties from different classes in DataTemplate.

<DataTemplate x:Key="DemoItemTemplate" x:DataType="local:DemoInfo">
   <NavigationViewItem Visibility="{Binding Visibility, Mode=TwoWay}" Content="{x:Bind Name}"/>
</DataTemplate>

DataType set as DemoInfo for this DataTemplate and Name value updated from DemoInfo.

I have tried view model as source and relative source binding. But Visibility property binding not working from ViewModel class. Any suggest how to achieve this?

Visibility="{Binding Visibility, Source={StaticResource viewModel}}"
MaxV
  • 2,601
  • 3
  • 18
  • 25
Kanniyappan P
  • 281
  • 1
  • 6

2 Answers2

0

AFAIK , you cant use multibinding in UWP , you can try to use Locator What is a ViewModelLocator and what are its pros/cons compared to DataTemplates?

Vladislav
  • 9
  • 2
0

How to bind two different class properties in DataTemplate

If you bind Visibility with StaticResource, please declare ViewModel class in your page Resources like the following.

ViewModel

public class ViewModel
{
    public ViewModel()
    {
        Visibility = false;
    }
    public bool Visibility { get; set; }
}

Xaml

<Page.Resources>
    <local:ViewModel x:Key="ViewModel" />
</Page.Resources>


<DataTemplate x:DataType="local:Item">
        <TextBlock
            Width="100"
            Height="44"
            Text="{x:Bind Name}"
            Visibility="{Binding Visibility, Source={StaticResource ViewModel}}" />
    </StackPanel>
</DataTemplate>

Update

If you want Visibility value changed dynamically at run-time, you need implement INotifyPropertyChanged interface for ViewModel class.

public class ViewModel : INotifyPropertyChanged
{
    public ViewModel()
    {
        Visibility = false;
    }
    private bool _visibility;
    public bool Visibility
    {
        get
        {

            return _visibility;
        }

        set
        {
            _visibility = value;
            OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged([CallerMemberName] string PropertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
    }
}

For more detail please refer Data binding in depth official document.

Nico Zhu
  • 32,367
  • 2
  • 15
  • 36
  • Thanks, but it working fine when application loaded and not working when the Visibility value changed dynamically at run-time. I have set mode as TwoWay and UpdateSourceTrigger as PropertyChanged in xaml and RaisePropertyChanged() used for Visibility property in ViewModel class. – Kanniyappan P Oct 26 '20 at 06:43
  • You need implement `INotifyPropertyChanged` interface for ViewModel class – Nico Zhu Oct 26 '20 at 06:57
  • @KanniyappanP, I have updated the case reply, please check. – Nico Zhu Oct 26 '20 at 08:04