2013-04-04 66 views
1

我有一个绑定到一个EnumerableRowCollection<T> WPF ComboBox组合框的约束该行。 SourcesOfValuesRow有一个值和一个描述,在组合中我想看到描述文本。 Text被绑定到将FamilyStatus作为int值保存的数据库,这就是我添加转换器的原因。使用转换器

我的问题是如果转换器可以使用来自combobox的itemsource从int值转换为字符串?我没有看到转换器知道组合的任何内容。与此同时,我写了转换器,再次从数据库中获取EnumerableRowCollection<TaxDataSet.SourcesOfValuesRow>,并找到匹配的描述 - 这不是最简单的方法! 有什么建议?

+0

您使用“EnumerableRowCollection ”而不是“字典”的任何特定原因?我知道如果你使用'Dictionary ',你可以使用'SelectedValuePath =“Key绑定”DisplayMemberPath =“Value”' – 2013-04-04 19:32:26

回答

3

在这种情况下,您最好使用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; 
} 
+0

我仍然不知道在转换器中写什么。我能否以另一种方式获取描述的int值,而不仅仅是从数据库中重新获取整个列表?在已经有组合框将项目源设置为数据库列表后,必须有最简单的方法。我可以在转换器中使用组合框的itemSource吗? – user2155957 2013-04-06 20:09:34

+0

从int值转换为描述? 老实说,在这一点上,你应该考虑[写一个枚举并给它显示文本](http://stackoverflow.com/questions/1331487/how-to-have-userfriendly-names-for-enumerations)。如果你设置你的枚举是从int派生的,你可以直接从db值转换为enum,绑定enum来显示,而你的转换器只是返回显示文本属性。 – 2013-04-09 14:46:17

0

无需使用任何转换器。它的工作我使用这个为:

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

哪里DisplayMemberPathTaxDataSet.SourcesOfValuesRowSelectedValuePath的字符串是int值。 SelectedValue是来自联系人表的值(而不是写入组合Text="{Binding FamilyStatus, Converter={StaticResource FamilyStatusStringConverter}})。