简体   繁体   English

绑定到 WPF 中静态类中的静态属性

[英]Binding to static property in static class in WPF

I have a problem with binding values from static properties from static class.我在绑定来自静态类的静态属性的值时遇到问题。

My class:我的课:

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

XAML: 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}}"/>

and when I run this code Background is set OK but the rest remains unchanged..当我运行此代码时,背景设置正常,但其余部分保持不变..

Problem is that your source properties are of a Color type and destination properties are Brush .问题是您的源属性是Color类型,目标属性是Brush You can create SolidColorBrush using your color like so:您可以使用您的颜色创建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>

You don't need to use static properties... you can declare a class using the Singleton pattern, so there can only be one instance, just like a static class.您不需要使用static属性...您可以使用Singleton模式声明一个类,因此只能有一个实例,就像static类一样。 Just use normal public CLR properties in this class... something like this (but with properties):只需在这个类中使用普通的public CLR 属性......像这样(但有属性):

public class StateManager
{
    private static StateManager instance;
    
    private StateManager() { }

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

    ...
}

Then only reference it from a base view model using the Instance property like this:然后只使用Instance属性从基本视图模型中引用它,如下所示:

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

Then you can access the properties in the UI simply, like this::然后您可以简单地访问 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}" ... />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM