C# 将静态资源绑定到WPF中的现有值
我想简化WPF中的绑定。比如说,我在App.xaml中创建了一个C# 将静态资源绑定到WPF中的现有值,c#,wpf,xaml,C#,Wpf,Xaml,我想简化WPF中的绑定。比如说,我在App.xaml中创建了一个fontfamine资源,它绑定到应用程序设置中的一个字符串值,以避免在每个窗口中都有一长行绑定表达式。但我发现我找不到一个方法来做到这一点 据说XAML2009中有一个x:Arguments,但这里不适用 我的做法: <DynamicResource x:Key="PrimaryFont" ResourceKey="{Binding PrimaryFont, Source={x:Static properties:Setti
fontfamine
资源,它绑定到应用程序设置中的一个字符串值,以避免在每个窗口中都有一长行绑定表达式。但我发现我找不到一个方法来做到这一点
据说XAML2009中有一个x:Arguments
,但这里不适用
我的做法:
<DynamicResource x:Key="PrimaryFont" ResourceKey="{Binding PrimaryFont, Source={x:Static properties:Settings.Default}, Converter={StaticResource StringToFontFamilyConverter}}"/>
这甚至不能编译
我不想在代码背后添加这些,因为我不想让一切看起来一团糟。可能吗
编辑:这不是的副本。
FontFamily
只是为了解释,在现实世界中,我想要简化绑定的元素不止一种,而且该元素可能不是新样式的好目标。事实证明,我在处理另一个问题的过程中找到了一个有趣的解决方案
Write by中提到的这个很棒的代理类是我的救命稻草:
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));
}
感谢您在中共享该发现。我看不出这是它的副本吗?不需要转换器,因此,绑定部分相对较小:
FontFamily=“{Binding MyFont,Source={x:Static p:Settings.Default}”
,假设设置中有字符串命名为MyFont
。默认值。另外,我使用了p
而不是properties
,使其更小。@Ron谢谢。现在我将在可应用的设置中使用它。
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));
}