Reputation: 1051
I have two comboboxes.
Xaml for 1st Combobox looks like:
<ComboBox IsEditable="True"
ItemsSource="{x:Static Fonts.SystemFontFamilies}" >
<ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type FontFamily}">
<TextBlock Text="{Binding}" FontFamily="{Binding}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
In the output of the above XAML I can see all the font-names in its own style. I want to do something similar for 2nd combobox also. Currently I have some items in 2nd combobox as below:
<ComboBox IsEditable="True">
<x:Static Member="FontStyles.Normal"/>
<x:Static Member="FontStyles.Italic"/>
<x:Static Member="FontStyles.Oblique"/>
</ComboBox>
How can I show each item in above combobox in its own style using Combobox.ItemTemplate or something similar without styling each item.
For e.g. my output should look something like:
Normal
Italic
Oblique
Upvotes: 2
Views: 930
Reputation: 6289
Take advantage of type converters: for most properties there's a converter that converts a string to a suitable value for the property. It's needed to be able to parse XAML (which is all strings) to types (think of writing something like Width="Auto"
while remembering that Width
is a double
value).
So, you can use something like this:
<ComboBox>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding }"
FontStyle="{Binding }" />
</DataTemplate>
</ComboBox.ItemTemplate>
<system:String>Normal</system:String>
<system:String>Italic</system:String>
<system:String>Oblique</system:String>
</ComboBox>
The binding for FontStyle
sets a string and then type converter springs into action and converts the string to an actual FontStyle
value to be used by the property.
NOTE: this might not work in .NET 3.0/3.5
EDIT : just remembered, in .NET 3.0/3.5, if there's a converter defined for the binding, then type converter is not working - the binding expects the converter to return the right type for the property. Not sure if it was changed in .NET 4.0/4.5 (probably not, and ,IMHO, shouldn't have - need to check it to verify).
Oh, and add this xmlns: xmlns:system="clr-namespace:System;assembly=mscorlib"
Upvotes: 3