How to bind two different class properties in DataTemplate

Viewed 384

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}}"
2 Answers

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.

Related