[英]How to bind a combobox with converter to a list in WPF
Here I'm trying to bind the combobox to a List Codes. 在这里,我试图将组合框绑定到列表代码。 The combobox is displaying: A & B
组合框显示:A和B.
<ComboBox ItemsSource="{Binding Path=Codes}"/>
public SettingsWindow()
{
InitializeComponent();
Codes = new List<Code> {Code.A, Code.B};
DataContext = this;
}
I have defined a converter to display a more understandable info in the combobox: 我已经定义了一个转换器,以在组合框中显示更易理解的信息:
public class CodeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var code = (Code)value;
string text;
if (code == Code.A)
{
text = "ACI318-99";
}
else
{
text = "ACI318-11";
}
return text;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
But I don't know how to use this converter in my XAML, so that I will have ACI318-99 & ACI318-11 in my combobox. 但是我不知道如何在我的XAML中使用这个转换器,所以我的组合框中会有ACI318-99和ACI318-11。
You should set the ItemTemplate of your Combobox, and use the Converter inside that. 您应该设置Combobox的ItemTemplate,并在其中使用Converter。
<ComboBox ItemsSource="{Binding Codes}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=., Converter={StaticResource converterInstance}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
here, converterInstance should be an instance of your custom converter in a resource dictionary. 这里,converterInstance应该是资源字典中自定义转换器的一个实例。
The Caliburn Micro convention is not that different but I just wanted to add it for future searchers. Caliburn Micro的惯例并没有那么不同,但我只想将它添加到未来的搜索者中。 (Path=. is not needed in my case)
(在我的情况下不需要Path =。)
<ComboBox x:Name="MyPropertyWithItems">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource converterInstance}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Try 尝试
<Window.Resources>
<CodeConverter x:Key="CodeConverter"/>
</Window.Resources>
and 和
<ComboBox ItemsSource="{Binding Path="Codes" Converter="{StaticResource CodeConverter}}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.