WPF FontFamily 格式问题
我正在尝试设置“字体系列”组合框的选定值,该值已使用以下 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>
我必须将组合框设置为的字段是一个字符串,但这会导致 FormatExceptions。谁能快速告诉我组合框需要什么类以及如何将字符串(例如“Arial”)转换为该格式?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望我正确理解了你的问题。
FontFamily 支持构造函数
,因此您应该能够使用 new FontFamily("Arial") 之类的方法从字符串转换为 FontFamily。
您可以将其放入一个实现 IValueConverter 的类中,该类在 FontFamily 和 String 之间进行转换。
要从 FontFamily 获取字符串,您可以访问 FamilyNames 属性来获取特定于特定文化的字体名称。
然后只需设置您的 FontFamily 绑定即可使用转换器。
Hope I've understood your question correctly.
FontFamily supports the constructor
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.
亚历克斯的回答听起来很好。
您还可以尝试 DependencyProperty:
然后您只需绑定 Combobox 的 SelectedItem 和 TextBlock 的 Text 和 FontFamily强>到“FontFamily”。
Alex' answer sounds very good.
You could also try a DependencyProperty:
Then you simply bind the SelectedItem of your Combobox and the Text and FontFamily of your TextBlock to "FontFamily".