1

例如,我有一个类似这样的视图模型:


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

public abstract class Person { }

public class Employee : Person { }

public class Boss : Person { }

根据我不想对我的 ListItemTemplate 进行一些更改的人的类型。我有一个像这样的值转换器:


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;
}

如何将 Visibilty 属性绑定到转换器?

我做过的事情:

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

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

1 回答 1

1

如果 DataContext 设置为您的 ViewModel 实例,则只需尝试以下操作:

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

此外,您可能想查看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;
    }
}

在xml中:

<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>

然后,您可以使用 personDataTemplateSelector 作为 ListView 或其他一些 ItemsControl 中 ItemTemplateSelector 的值。

<ContentPresenter Content="{Binding}" 
                  ContentTemplateSelector="{StaticResource ResourceKey=personDataTemplateSelector}" />
于 2012-07-17T18:34:39.467 回答