Here I'm trying to bind the combobox to a List Codes. The combobox is displaying: 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.
You should set the ItemTemplate of your Combobox, and use the Converter inside that.
<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.
The Caliburn Micro convention is not that different but I just wanted to add it for future searchers. (Path=. is not needed in my case)
<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}}"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.