我知道这篇文章:TextBox FontFamily Binding ,看起来和我的问题类似,但我的情况更简单,我想将 TextBox 控件的 FontFamily 属性绑定(bind)到 ComboBox,当 ComboBox 的值更改时,TextBox 的内容也会相应更改。我没有使用虚拟机或依赖属性,我遵循了本教程:https://dotnetstories.wordpress.com/2011/07/31/using-type-converters-in-wpf/
并想出了:
<Window x:Class="NumericControlTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:NumericControlTest"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:FontFamilyConversions x:Key="FontFamilyConversions" />
</Window.Resources>
<DockPanel>
<ComboBox DockPanel.Dock="Top" x:Name="Fonttype" >
<ComboBoxItem IsSelected="True">Arial</ComboBoxItem>
<ComboBoxItem>Batang</ComboBoxItem>
<ComboBoxItem>BatangChe</ComboBoxItem>
<ComboBoxItem>Gungsuh</ComboBoxItem>
<ComboBoxItem>GungsuhChe</ComboBoxItem>
<ComboBoxItem>Courier New</ComboBoxItem>
</ComboBox>
<TextBox x:Name="editor" FontSize="16" FontFamily="{Binding Path=SelectedValue, ElementName=Fonttype, Mode=OneWay, Converter={StaticResource FontFamilyConversions}}" >
</TextBox>
</DockPanel>
using System.Windows.Data;
using System.Windows.Media;
namespace NumericControlTest
{
class FontFamilyConversions : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FontFamily fontfamily = new FontFamily("Verdana");
if (value != null)
{
fontfamily = new FontFamily(value.ToString());
}
return fontfamily;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}
但是它不起作用,在我更改 ComboBox 的值后,什么也没有发生。
感谢您的宝贵时间。
最佳答案
return fontfamily;
上的断点会表明您没有从 value.ToString()
得到您所期望的结果。您需要获取Content
来自ComboBoxItem
:
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
FontFamily fontfamily = new FontFamily("Verdana");
ComboBoxItem selectedFont = value as ComboBoxItem;
if (selectedFont != null)
{
fontfamily = new FontFamily(selectedFont.Content.ToString());
}
return fontfamily;
}
您可以通过添加 <FontFamily>
来完全避免使用转换器。对象直接到 ComboBox
:
<ComboBox DockPanel.Dock="Top" x:Name="Fonttype" SelectedIndex="0">
<FontFamily>Arial</FontFamily>
<FontFamily>Segoe UI</FontFamily>
</ComboBox>
然后绑定(bind)到SelectedValue
无需转换器。
FontFamily="{Binding Path=SelectedValue, ElementName=Fonttype, Mode=OneWay}"
或者您可能想自动获取已安装字体的列表:
<ComboBox DockPanel.Dock="Top" x:Name="Fonttype" ItemsSource="{x:Static Fonts.SystemFontFamilies}" SelectedIndex="0" />
虽然不太可能SystemFontFamilies
将被排序,所以你需要 use a CollectionViewSource
to sort .
关于c# - WPF - 将 TextBox 的 FontFamily 绑定(bind)到 ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733780/