[英]WPF FontFamily Format question
I'm trying to set the selected value of my Font Family combobox, which has been populated with the following XAML: 我正在尝试设置我的Font Family组合框的选定值,该组合框已填充以下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. 我必须将组合框设置为字符串,但这会导致FormatExceptions。 Can anyone quickly tell me what class the combobox will be expecting and also how to convert a string eg "Arial" to that format?
任何人都可以快速告诉我组合框将期待什么类,以及如何将字符串例如“Arial”转换为该格式?
Hope I've understood your question correctly. 希望我能正确理解你的问题。
FontFamily supports the constructor FontFamily支持构造函数
FontFamily(String familyName);
So you should be able to use something like new FontFamily("Arial")
to convert from a string to a FontFamily. 所以你应该可以使用像
new FontFamily("Arial")
这样的东西来从字符串转换为FontFamily。
You could put that in a class which implements IValueConverter
which converts between FontFamily and String. 你可以将它放在一个实现
IValueConverter
的类中,该类在FontFamily和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. 要从FontFamily获取字符串,您可以访问FamilyNames属性以获取特定文化特定字体的名称。
Then just set your FontFamily binding to use the converter. 然后只需设置FontFamily绑定即可使用转换器。
Alex' answer sounds very good. 亚历克斯的回答听起来非常好。
You could also try a DependencyProperty: 您还可以尝试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". 然后,您只需将Combobox的SelectedItem 和 TextBlock的Text和FontFamily绑定到“FontFamily”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.