将静态资源绑定到 WPF 中的现有值 [英] Binding a static resource to an existing value in WPF
问题描述
我想简化 WPF 中的绑定.比如说,我在 App.xaml 中创建了一个 FontFamily
资源,它绑定到应用程序设置中的一个字符串值,以避免在每个窗口中出现一长串绑定表达式.但我发现我找不到办法做到这一点.
I want to simplify bindings in WPF. Say, I'm creating a FontFamily
resource in App.xaml which binds to a string value in the application settings, to avoid a long line of binding expression in every window. But I found that I couldn't find a way to do that.
据说 XAML 2009 中有一个 x:Arguments
,但这在此处不适用.
It is said that there's a x:Arguments
in XAML 2009, but that does not apply here.
我的方法:
<DynamicResource x:Key="PrimaryFont" ResourceKey="{Binding PrimaryFont, Source={x:Static properties:Settings.Default}, Converter={StaticResource StringToFontFamilyConverter}}"/>
失败,抛出一个 XamlParseException
.
<FontFamily x:Key="PrimaryFont">
<Binding Path="PrimaryFont" Source="{x:Static properties:Settings.Default}" Converter="{StaticResource StringToFontFamilyConverter}"/>
</FontFamily>
这甚至无法编译.
我不想在后面的代码中添加它,因为我不想让一切看起来一团糟.这可能吗?
I don't want to add that in code behind, because I don't want to make everything look like a mess. Is that possible?
这不是设置全局字体系列的副本.FontFamily
仅用于解释目的,在现实世界中,我想要简化绑定的元素不止一种,并且该元素可能不是新样式的好目标.
this is not a duplicate of Setting global font family. The FontFamily
is just for explaining purpose, in real world there will be more than one kind of element I want to simplify the binding on, and the element might not be a good target for a new style.
推荐答案
原来我在处理另一个问题的过程中找到了一个有趣的解决方案.
Turns out I found an interesting solution in the process of dealing with another problem.
这篇文章 由 @ThomasLevesque 撰写是我的救命稻草:
This awesome little proxy class mentioned in this article written by @ThomasLevesque is my life saver:
public class BindingProxy : Freezable
{
#region Overrides of Freezable
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
}
#endregion
public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
// Using a DependencyProperty as the backing store for Data. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DataProperty =
DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}
感谢 @mkoertgen 分享在 这个答案.
这篇关于将静态资源绑定到 WPF 中的现有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!