C# 在组合框中的绑定项目上使用转换器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9448862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Use converter on bound items in combobox
提问by lebhero
i have a combobox which is bound to a datatable column like this:
我有一个绑定到数据表列的组合框,如下所示:
ComboBox.DataContext = DataDataTable;
ComboBox.DisplayMemberPath = DataDataTable.Columns["IDNr"].ToString();
The IDNr in the Column always starts with 4 letters followed with the ID Number (ex. BLXF1234) . I need to display the items in Combobox without the Letters (i need 1234 to be displayed in the combobox).
列中的 IDNr 始终以 4 个字母开头,后跟 ID 号(例如 BLXF1234)。我需要在没有字母的组合框中显示项目(我需要在组合框中显示 1234)。
So i wrote a converter :
所以我写了一个转换器:
class IDPrefixValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
string s = value.ToString();
if (s.Contains("BL"))
{
return s.Substring(4);
}
else
{
return s;
}
}
return "";
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
No, how can i tell the combobox to use the converter to display the items ? i tried this in the Xaml:
不,我如何告诉组合框使用转换器来显示项目?我在 Xaml 中试过这个:
ItemsSource="{Binding}"
DisplayMemberPath="{Binding Converter={StaticResource IDPrefixValueConverter}}"
But still not working ...any ideas ? Thanks
但仍然无法正常工作......有什么想法吗?谢谢
采纳答案by Martin Liversage
You can modify the ItemTemplateof the ComboBoxand use your converter:
您可以修改ItemTemplate的ComboBox,用你的转换器:
<ComboBox ItemsSource="{Binding}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource IDPrefixValueConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Each item is bound to the items in the ItemsSource. By using the converter in the binding you are able to perform the conversion you want.
每个项目都绑定到 中的项目ItemsSource。通过在绑定中使用转换器,您可以执行所需的转换。

