【问题标题】:Visibility depening on generic DataType可见性取决于通用数据类型
【发布时间】:2017-09-28 20:07:30
【问题描述】:

我有一个 ModuleType,它有两个继承的 ModuleType:PayModule 和 FreeModule。

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

<TreeView ItemsSource="{Binding ListOfModules}">

在我的 DataTemplates 中有几个 Expander。仅当 TreeViewItem 具有 DataType PayModule 时,其中之一才可见

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

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

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

例如,我想通过 ConverterParameter 传递所需的类型,然后对其进行转换,例如:

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

-

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

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

    它应该像这样工作:

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

    【讨论】:

      【解决方案2】:

      parameter 的类型将始终是Type 类型,只需将其转换为(Type)parameter。另外,由于is (Type)parameter 不起作用,您可以使用它:

      if ((parameter as Type)?.IsAssignableFrom(value.GetType()) ?? false)
          return Visibility.Visible;
      

      编辑:

      只是为了指出差异:Clemens 的回答要容易得多,如果您只想要一种特定类型,请使用该类型。我的也适用于继承的类型。

      编辑 2:

      不再正确,结果现在将相同:)

      【讨论】:

      • typeof(parameter) 不会编译。
      • @Clemens 是的,我写的有点过于字面了 - 我的意思是参数的类型将始终是类型 Type
      • 除非您没有指定它。最好使用parameter as Type,可以为null。
      • @Clemens 够公平
      猜你喜欢
      • 2023-03-23
      • 2012-10-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      • 2017-11-28
      • 1970-01-01
      • 2018-04-09
      • 2020-05-07
      相关资源
      最近更新 更多