简体   繁体   中英

Binding a value converter to the object or the type

For example i have a viewmodel with something like this:


public class MyViewModel
{
    public ObservableCollection { get; set; }
}

public abstract class Person { }

public class Employee : Person { }

public class Boss : Person { }

Depending on the type of the person I wan't some changes to my ListItemTemplate. I have a value converter like this:


public object Convert(object value, Type targetType, object parameter, string language)
{
       if (value == null) return Visibility.Collapsed;

      return value is Boss ? Visibility.Visible : Visibility.Collapsed;
}

How do I bind the Visibilty property to the converter?

Things i've done:

<Border Visibility="{Binding Path=self, Converter={StaticResource BossVisibilityConverter}}">

<Border Visibility="{Binding Path=this, Converter={StaticResource BossVisibilityConverter}}">

if the DataContext is set to your ViewModel instance, then just try the following:

<Border Visibility="{Binding Converter={StaticResource BossVisibilityConverter}}">

Also, you might want to look into a DataTemplateSelector

public class PersonDataTemplateSelector: DataTemplateSelector
{

    public DataTemplate BossTemplate { get; set; }
    public DataTemplate EmployeeTemplate { get; set; }

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        DataTemplate selectedTemplate = null;

        if (item is Boss)
        {
            selectedTemplate = BossTemplate;
        }
        else
        {
            selectedTemplate = EmployeeTemplate;
        }

        return selectedTemplate;
    }
}

in xaml:

<controls:PersonDataTemplateSelector x:Key="personDataTemplateSelector"
                                       BossTemplate="{StaticResource ResourceKey=BossTemplate}" 
                                       EmployeeTemplate="{StaticResource ResourceKey=EmployeeTemplate}" />

<DataTemplate x:Key="BossTemplate">
   ... Template here
</DataTemplate>

<DataTemplate x:Key="EmployeeTemplate">
   ... Template here
</DataTemplate>

Then you can use the personDataTemplateSelector as the value of an ItemTemplateSelector in a ListView, or some other ItemsControl.

<ContentPresenter Content="{Binding}" 
                  ContentTemplateSelector="{StaticResource ResourceKey=personDataTemplateSelector}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM