可见性取决于通用DataType

时间:2017-09-28 11:41:33

标签: c# .net wpf xaml

我有一个带有两个继承的ModuleTypes的ModuleType:PayModule和FreeModule。

我还有一个带有这个ItemSource的TreeView:

<Expander Header="{Binding PayModuleItem.Name}"
  Visibility="{Binding PayModuleItem, Converter={StaticResource TypeToVisibleConverter}}">

在我的DataTemplates中有几个Expander。只有在TreeViewItem具有DataType PayModule

时才能看到其中一个
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    if (value == null)
        return Visibility.Collapsed;

    if (value is PayModule)
        return Visibility.Visible;

    return Visibility.Collapsed;
}

这是我的TypeToVisibleConverter。它是特定类型的。是否可以获得通用转换器?

<Expander Header="{Binding PayModuleItem.Name}"
   Visibility="{Binding PayModuleItem, Converter={StaticResource TypeToVisibleConverter}, 
   ConverterParameter={x:Type my:PayModule}}">

我希望通过ConverterParameter传递所需类型,然后转换为它,例如:

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

    if (value is typeOf(parameter)
        return Visibility.Visible;

    return Visibility.Collapsed;
}

-

{{1}}

2 个答案:

答案 0 :(得分:3)

它应该像这样工作:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    return value != null && value.GetType() == parameter as Type
        ? Visibility.Visible
        : Visibility.Collapsed;
}

如果您还希望能够检查基类或接口:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    var type = parameter as Type;

    return type != null && type.IsInstanceOfType(value)
        ? Visibility.Visible
        : Visibility.Collapsed;
}

答案 1 :(得分:1)

parameter的类型始终为类型Type,只需将其(Type)parameter强制转换为is (Type)parameter。此外,由于if ((parameter as Type)?.IsAssignableFrom(value.GetType()) ?? false) return Visibility.Visible; 无效,您可以使用此功能:

@property (strong, nonatomic) IBOutlet UILabel *name;

编辑:

只是指出差异:克莱门斯&#39;答案要容易得多,如果您只想要一个特定类型,请使用该类型。我也会为继承类型工作。

编辑2:

不再是真的,现在结果将是相同的:)

相关问题