How to bind two different class properties in DataTemplate

683 views Asked by At

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}}"
3

There are 3 answers

0
Signalist On

I could be wrong, but I thought the Visibility property had a dedicated enum that contains all the possible options (Visibility Enum) for the Visibility property. So, your binding might be working just fine, but the Type of the bound property would need to be of type Visibility using System.Windows.

On a side note, I wouldn't put a visibility property in the view model anyway. I think a more standard approach would be to have a visibility DependencyProperty in the immediate code behind of the view for your binding.

3
Nico Zhu On

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.

0
Vladislav On

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?