【问题标题】:Binding to MainWindowViewModel property from app.xaml从 app.xaml 绑定到 MainWindowViewModel 属性
【发布时间】:2019-10-14 04:46:33
【问题描述】:

我正在尝试全局更改字体大小。为此,我在 app.xaml 中添加了样式。这里我的FontSz 属性在 MainWindowViewModel 中。有没有办法使这种绑定成为可能?

<Application.Resources>
    <Style TargetType="{x:Type Control}" x:Key="baseStyle">
        <Setter Property="FontSize" Value="{Binding Path=???.FontSz}" />
    </Style>
    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource baseStyle}"/>
    <Style TargetType="{x:Type Label}" BasedOn="{StaticResource baseStyle}"/>
</Application.Resources>

【问题讨论】:

  • 您是否尝试在运行时由用户更改字体大小?
  • @Insane 是的。它由用户设置。

标签: wpf data-binding


【解决方案1】:

您需要为此使用 DynamicResouce。如下添加系统命名空间

xmlns:system="clr-namespace:System;assembly=mscorlib"

<Application.Resources>

    <system:Double x:Key="FontSz">20</system:Double>

    <Style x:Key="baseStyle" 
           TargetType="{x:Type Control}">
        <Setter Property="FontSize" 
                Value="{DynamicResource FontSz}"/>
    </Style>

    <Style TargetType="{x:Type Button}"
           BasedOn="{StaticResource baseStyle}"/>

    <Style TargetType="{x:Type Label}" 
           BasedOn="{StaticResource baseStyle}"/>

</Application.Resources>

MainWindowViewModel 在您的命令执行中,添加以下代码:

Application.Current.Resources["FontSz"] = 18d;

您可以将字体大小从 18d 更改为用户在 MainViewModel 中选择的字体大小。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2014-11-12
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多