我的目标是通过 DependencyProperties 操作我的应用程序的文本样式。我有一个图表,其中的文本要在大小、字体系列、颜色等方面进行操作。所以我想使用类似于 Word 等富文本编辑器的界面。
我在我的 TextStyleVM http://shevaspace.blogspot.com/2006/12/i-have-some-fun-with-formattedtext_14.html中使用此代码
所以我有一个 FontFamilyProperty 和一个 Getter 和 Setter:
public static DependencyProperty FontFamilyProperty =
DependencyProperty.Register(
"FontFamily",
typeof(FontFamily),
typeof(OutlinedText),
new FrameworkPropertyMetadata(
SystemFonts.MessageFontFamily,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.AffectsMeasure),
new ValidateValueCallback(IsValidFontFamily));
public FontFamily FontFamily
{
get { return (FontFamily)base.GetValue(FontFamilyProperty); }
set { base.SetValue(FontFamilyProperty, value); }
}
然后是一个 ToStyle 方法,它为图表的标签设置样式,这些标签要被操作:
Style style = new Style();
Binding fontFamilyBinding = new Binding("FontFamily");
fontFamilyBinding.Source = this;
Setter fontFamilySetter = new Setter();
fontFamilySetter.Property = TextBlock.FontFamilyProperty;
fontFamilySetter.Value = fontFamilyBinding;
style.Setters.Add(fontFamilySetter);
return style;
现在这适用于文本框。文本框显示当前的 FontFamily,如果我在文本框中输入新的、有效的 FontFamily(如 Arial),则标签的 FontFamily 会更改。
但是,我想要的是一个组合框,它显示 SystemFonts 并且我可以在其中为我的标签选择一个 FontFamily。但是,绑定似乎不起作用。既不显示系统字体,也不显示标签的当前字体。组合框只是空的。
这是我的 xaml:
<r:RibbonLabel Content="FontFamily" />
<!--these do not work-->
<r:RibbonComboBox SelectedItem="{Binding FontFamily}"/>
<r:RibbonComboBox ItemsSource="{Binding FontFamily}"/>
<!--this works-->
<r:RibbonTextBox Text="{Binding FontFamily}"/>
现在,我假设我必须在 ToStyle 方法中为 ComboBox 设置不同的 Setter。但我不知道,是哪一个。也许是这样的:
fontFamilySetter.Property = ComboBox.ItemSource;
但是,如果我设置该属性,文本框仍然有效。那么这是错误的起点吗?如果有人能提示我一些有关使用 ToStyle 方法中使用的 Style-、Setter-、Binding-keywords 的文档,我也将不胜感激,因为这是我正在使用的其他人的代码。