【问题标题】:C# UWP data binding in TextBox ResourcesTextBox 资源中的 C# UWP 数据绑定
【发布时间】:2021-09-09 16:44:01
【问题描述】:

我在我的应用中实现了一个浅色/深色主题,用户可以按下浅色或深色按钮,所有应用颜色都会改变。我通过将 SolidColorBrush 绑定到每个元素的背景和前景来做到这一点,例如

在视图模型中:

private SolidColorBrush fontColour;
        public SolidColorBrush FontColour
        {
            get { return fontColour; }
            set
            {
                fontColour = value;
                OnPropertyChanged(nameof(FontColour));
            }
        }

在 xaml 中:

<TextBox Text="{Binding EventLog}"
                             Foreground="{Binding FontColour}"
                             Background="{Binding ColourTheme5}"/>

这按预期工作。但是,当我尝试在 TextBox.Resources 中做同样的事情时,绑定根本不起作用,例如

(TextControlForegroundPointerOver 的绑定不起作用)

<TextBox Text="{Binding EventLog}"
                             Foreground="{Binding FontColour}"
                             Background="{Binding ColourTheme5}">

                        <TextBox.Resources>

                            <SolidColorBrush x:Key="TextControlForegroundPointerOver"
                                             Color="{Binding FontColour}"
                                             Opacity="1" />
                        </TextBox.Resources>
                    </TextBox>

【问题讨论】:

    标签: c# xaml data-binding uwp


    【解决方案1】:

    您正在重新发明轮子。 Xaml 具有可以在页面级别设置的Theme ResourcesRequestedTheme 属性。

    【讨论】:

      【解决方案2】:

      我几乎可以肯定,TextBox.Resources 不是 DependencyProperty,因此无法绑定。

      如果您想在编译时设置它,请使用代码初始化(就像您放在最底部的示例一样)。

      如果你想在运行时设置它,你必须在你放置 TextBox 的窗口/用户控件的构造函数中以编程方式进行设置。这应该可以。

      编辑:我错过了问题的“浅色/深色主题”部分,因此我想补充一下:

      Windows 社区工具包中有很多关于主题的内容、更多文档以及示例应用程序中的一部分,您可以在 https://docs.microsoft.com/en-us/windows/communitytoolkit/helpers/themelistener 找到。

      【讨论】:

      • 我也需要能够在运行时更改它。例如。用户从浅色模式变为深色模式,因此我需要更改颜色值
      • @DavidAndrewThorpe 我编辑了我的答案以包含一个正确的链接,看看那个。无论如何,您不会交换整个资源字典。这是个坏主意。您应该为此使用绑定并覆盖默认模板。
      • 干杯哥们,等我回到电脑前看看。
      猜你喜欢
      • 2020-07-04
      • 2017-01-29
      • 2017-06-15
      • 1970-01-01
      • 2010-12-09
      • 1970-01-01
      • 2014-07-05
      • 2023-04-10
      • 2018-09-03
      相关资源
      最近更新 更多