I'm trying to set the selected value of my Font Family开发者_如何学运维 combobox, which has been populated with the following XAML:
<ComboBox ItemsSource="{x:Static Fonts.SystemFontFamilies}" Name="cboFont">
<ComboBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel MinWidth="256" />
</ItemsPanelTemplate>
</ComboBox.ItemsPanel>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding}" FontFamily="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
The field I have to set the combobox to is a string, but that causes FormatExceptions. Can anyone quickly tell me what class the combobox will be expecting and also how to convert a string e.g. "Arial" to that format?
Hope I've understood your question correctly.
FontFamily supports the constructor
FontFamily(String familyName);
So you should be able to use something like new FontFamily("Arial")
to convert from a string to a FontFamily.
You could put that in a class which implements IValueConverter
which converts between FontFamily and String.
To get from FontFamily to string, you can access the FamilyNames property to get a name for the font which is specific to a particular culture.
Then just set your FontFamily binding to use the converter.
Alex' answer sounds very good.
You could also try a DependencyProperty:
public FontFamily FontFamily
{
get { return (FontFamily)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
public static DependencyProperty FontFamilyProperty =
DependencyProperty.Register(
"FontFamily",
typeof(FontFamily),
typeof(YourClassVM),
new FrameworkPropertyMetadata(SystemFonts.MessageFontFamily
, FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure)
);
Then you simply bind the SelectedItem of your Combobox and the Text and FontFamily of your TextBlock to "FontFamily".
精彩评论