【问题标题】:WPF bound combobox using converter使用转换器的 WPF 绑定组合框
【发布时间】:2013-04-04 19:02:11
【问题描述】:

我有一个绑定到EnumerableRowCollection<T>ComboBox

ComboFamilyStatus.ItemsSource = EnumerableRowCollection<TaxDataSet.SourcesOfValuesRow> coll;

我的 xaml 看起来像这样:

<ComboBox Name="ComboFamilyStatus" DisplayMemberPath="Description" 
          Text="{Binding FamilyStatus, Converter={StaticResource FamilyStatusStringConverter}}">

我使用DisplayMemberPath 来显示行的描述。 SourcesOfValuesRow 有一个值和一个描述,在组合中我想查看描述文本。文本绑定到 FamilyStatus 保存为 int 值的数据库,这就是我添加转换器的原因。

我的问题是转换器是否可以使用组合框中的 itemsource 从 int 值转换为字符串?我看不到转换器对组合一无所知。与此同时,我编写了转换器以再次从数据库中获取EnumerableRowCollection&lt;TaxDataSet.SourcesOfValuesRow&gt; 并在那里找到匹配的描述 - 这不是最简单的方法! 有什么建议吗??

【问题讨论】:

  • 您使用EnumerableRowCollection&lt;T&gt;而不是Dictionary&lt;int, string&gt;的任何特殊原因?我知道如果你使用Dictionary&lt;T1, T2&gt;,你可以使用SelectedValuePath="Key" DisplayMemberPath="Value"绑定

标签: wpf binding combobox converter


【解决方案1】:

在这种情况下,您最好使用DataTemplate,而不是Converter

您已经有一个数据类。只需使用 DataTemplate 插入绑定到 int 值的 Textblock,然后在此处应用您的转换器。

<ComboBox>
   <ComboBox.ItemTemplate>
      <DataTemplate DataType="{x:Type local:TaxDataSet.SourcesOfValuesRow}">
         <TextBlock Text="{Binding FamilyStatus, Converter={StaticResource FamilyStatusStringConverter}}"/>
      </DataTemplate>
   </ComboBox.ItemTemplate>
<ComboBox>

将您的 SourcesOfValuesRow FamilyStatusProperty 更改为枚举。从 int 派生可以直接转换它。

enum FamilyStatusValues : int
{
   [Description("Married")]
   Married,
   [Description("Divorced")]
   Divorced,
   [Description("Living Together")]
   LivingTogether
}

然后在您的转换器中使用此代码

ConvertTo(object value, ...)
{
   FieldInfo field = value.GetType().GetField(value.ToString());
   object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), true));
   if(attribs.Length > 0)
   {
       return ((DescriptionAttribute)attribs[0]).Description;
   }
   return string.Empty;
}

【讨论】:

  • 我仍然不知道在转换器中写什么。我能否以另一种方式获取描述的 int 值,而不是再次从数据库中获取整个列表?在我已经拥有将项目源设置为数据库列表的组合框之后,必须有一种最简单的方法来执行此操作。我可以在转换器中使用组合框的 itemSource 吗?
  • 从 int 值转换为描述?老实说,此时您应该考虑writing an enum and giving it display text。如果将枚举设置为从 int 派生,则可以直接从 db 值转换为枚举,将枚举绑定到显示,您的转换器只返回显示文本属性。
【解决方案2】:

无需使用任何转换器。它对我有用:

<ComboBox Name="FamilyStatus" Grid.Row="7" Grid.Column="1" ItemsSource="{Binding Source={StaticResource comboProvider}}"
            SelectedValuePath="Value" DisplayMemberPath="Description" SelectedValue="{Binding FamilyStatus}">

其中DisplayMemberPath 是来自TaxDataSet.SourcesOfValuesRow 的字符串,SelectedValuePath 是 int 值。 SelectedValue 是联系人表中的值(而不是写在组合 Text="{Binding FamilyStatus, Converter={StaticResource FamilyStatusStringConverter}} 中)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多