【问题标题】:Handle different content in XAML binding处理 XAML 绑定中的不同内容
【发布时间】:2019-01-23 16:55:02
【问题描述】:

我在 XAML 中有一个与 Validation.Errors 的绑定。 有时这似乎是一个字符串,有时它是一个字符串列表。

如果它是单个字符串,则以下代码可以正常工作。 对于字符串列表,我只需将“System.Generic.List”作为项目控件中的一个项目。

如果我将 DisplayMemberPath 更改为“ErrorContent[0]”,如果它是一个列表,它会成功显示第一个字符串,但如果它恰好是一个字符串,我当然只会得到第一个字符。

问题。如何让它在 XAML 中处理这两种情况(单字符串类型和列表类型)?

 <ItemsControl     
     x:Name="ErrorDisplay"                                      
     ItemsSource="{TemplateBinding Validation.Errors}"   
     DisplayMemberPath="ErrorContent"
     Foreground="Red" 
     FontSize="12">
 </ItemsControl>

【问题讨论】:

标签: .net wpf typescript xaml binding


【解决方案1】:

首先,您需要为StringList 定义两个DataTemplate

<DataTemplate x:Key="singleObject">
    <TextBlock Text="{Binding}"/>
</DataTemplate>

<DataTemplate x:Key="collection">
    <Listbox ItemsSource="{Binding}"/>
</DataTemplate>

然后实现一个DataTemplateSelector 类并将其声明为资源。

public class MyDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate
        SelectTemplate(object item, DependencyObject container)
    {
        FrameworkElement element = container as FrameworkElement;

        if (element != null && item != null)
        {
            var ie = item as IEnumerable;
            if (ie == null)
                return
                    element.FindResource("singleObject") as DataTemplate;
            else
                return
                    element.FindResource("collection") as DataTemplate;
        }

        return null;
    }
}

<right namespace prefix:MyDataTemplateSelector x:Key="myDataTemplateSelector"/>

最后,将您的DataTemplateSelector 设置为您的ItemsControl

<ItemsControl x:Name="ErrorDisplay" FontSize="12"
              ItemsSource="{TemplateBinding Validation.Errors}"   
              DisplayMemberPath="ErrorContent" Foreground="Red"
              ItemTemplateSelector="{StaticResource myDataTemplateSelector}"/>

【讨论】:

  • 谢谢,效果很好。 Validation.Errors 的类型是 ValidationError 而不是 String / List 但是改变你的答案来代替它是很容易的。项目控件不接受 ItemTemplateSelector 并同时使用 DisplayMemberPath。我刚刚从 ItemsControl 中删除了 DisplaymemberPath,而是让 DataTemplates 绑定到 ErrorContent。在我的例子中,我意识到 Validation.Errors 类型是 ValidationError,所以我不得不更改选择器类来查看项目的 ErrorContent 属性。
猜你喜欢
  • 2016-02-20
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 2012-01-21
  • 2013-08-16
  • 2017-06-05
  • 2011-05-25
相关资源
最近更新 更多