【问题标题】:Binding to static property in static class in WPF绑定到 WPF 中静态类中的静态属性
【发布时间】:2014-01-29 16:12:21
【问题描述】:

我在从静态类的静态属性中绑定值时遇到问题。

我的班级:

namespace MyNamespace.Data
{
    public static class MySettings
    {
        public static Color BackgroundColor { get; set; }
        public static Color FontColor { get; set; }
    }
}

XAML:

<Page ...
       xmlns:colors="clr-namespace:MyNamespace.Data"
      ...>
 ...
<Button Grid.Column="0" Content="Text"
        Background="{Binding Source={x:Static s:MySettings.BackgroundColor}}"
        Foreground="{Binding Source={x:Static s:MySettings.FontColor}}"
        BorderBrush="{Binding Source={x:Static s:MySettings.FontColor}}"/>

当我运行此代码时,背景设置正常,但其余部分保持不变..

【问题讨论】:

    标签: c# wpf xaml binding static


    【解决方案1】:

    问题是您的源属性是Color 类型,而目标属性是Brush。您可以使用您的颜色创建SolidColorBrush,如下所示:

    <Button Content="Text">
        <Button.Background>
            <SolidColorBrush Color="{Binding Source={x:Static s:MySettings.BackgroundColor}}"/>
        </Button.Background>
        <Button.Foreground>
            <SolidColorBrush Color="{Binding Source={x:Static s:MySettings.FontColor}}"/>
        </Button.Foreground>
        <Button.BorderBrush>
            <SolidColorBrush Color="{Binding Source={x:Static s:MySettings.FontColor}}"/>
        </Button.BorderBrush>
    </Button>
    

    【讨论】:

      【解决方案2】:

      您不需要使用static 属性...您可以使用Singleton 模式声明一个类,因此只能有一个实例,like static班级。只需在此类中使用普通的public CLR 属性...类似这样(但带有属性):

      public class StateManager
      {
          private static StateManager instance;
          
          private StateManager() { }
      
          public static StateManager Instance
          {
              get { return instance ?? (instance = new StateManager()); }
          }
      
          ...
      }
      

      然后仅使用 Instance 属性从基本视图模型中引用它,如下所示:

      public StateManager StateManager
      {
          get { return StateManager.Instance; }
      }
      

      然后你可以简单地访问 UI 中的属性,像这样::

      <Ribbon:RibbonCheckBox Grid.Row="1" Label="Audit fields" 
          IsChecked="{Binding StateManager.AreAuditFieldsVisible}" ... />
      <Ribbon:RibbonCheckBox Grid.Row="2" Label="ISRCs on results" 
          IsChecked="{Binding StateManager.AreIsrcsVisibleOnSearchResults}" ... />
      

      【讨论】:

      • +1 这正是我正在寻找的——即在绑定中使用常规(非静态)类。为什么不需要在Binding 标记中指定"Source={...
      • 如果您在 App.xaml 代码后面需要这个实例怎么办?需要在 OnStartup 事件中设置静态变量。
      • @LuckyLuke82,你可以在任何你喜欢的地方使用它。它只是一个类,将在第一次使用时初始化。
      猜你喜欢
      • 2015-10-15
      • 2014-09-10
      • 2012-10-15
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-08-26
      • 2021-01-17
      相关资源
      最近更新 更多