我的目标是通过DependencyProperties操作我的应用程序的文本样式。我得到了一个图表,其中的文字是在大小,fontfamily,颜色等操作。所以我想使用类似于丰富的文本编辑器,如Word的界面。在Combobox中显示FontFamily
我使用这个代码在我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;
现在这适用于TextBox。该文本框显示当前的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方法组合框。但我不知道哪一个。也许有点像这样:
fontFamilySetter.Property = ComboBox.ItemSource;
但是,如果我设置该属性,文本框仍然工作。那么这是否是错误的地方?如果有人能够提示我使用ToStyle方法中使用的这些Style-,Setter-,Binding-key-words的文档,我也会很感激,因为这是某人删除了我正在使用的代码。
这工作,当然,不过这并不提供任何方式修改我的FontFamilyProperty。换句话说:如何将此ComboBox绑定到名为FontFamilyProperty的DependencyProperty? 如果我将SelectedValue或SelectedItem设置为FontFamily,我会得到无效的转换异常:“System.Windows.Media.FontFamily”无法转换为“Microsoft.Windows.Controls.Ribbon.RibbonComboBoxItem” – Torsten 2010-06-08 11:01:57
Hi Torsten;我已经添加了一个dp绑定的例子。除非你想做一些非常不寻常的事情,否则看起来没有任何问题。 – 2010-06-08 15:05:24
感谢您的热心支持。 我将我的代码迁移到Fluent功能区,在那里您的示例工作。我在这里有一些小的变化,但它是基于你的想法: 1.我必须在SelectedItem绑定上设置Mode = TwoWay 2.我在我的DP上使用了FrameworkPropertyMetadata(请参阅shevaspace.blogspot.com中的链接我的startpost),UIPropertyMetadata也可以工作,但是,我认为。 我真的很感谢你的帮助。 – Torsten 2010-07-19 07:31:49