c# - WPF 更改具有附加属性的控件的背景

标签 c# wpf attached-properties brushes

当 bool 变量为 true 时,我需要更改标签和按钮的背景(如果为 false,则返回默认颜色)。所以我写了一个附加属性。到目前为止看起来像这样:

public class BackgroundChanger : DependencyObject
{
    #region dependency properties
    // status
    public static bool GetStatus(DependencyObject obj)
    {
        return (bool)obj.GetValue(StatusProperty);
    }
    public static void SetStatus(DependencyObject obj, bool value)
    {
        obj.SetValue(StatusProperty, value);
    }
    public static readonly DependencyProperty StatusProperty = DependencyProperty.RegisterAttached("Status",
                     typeof(bool), typeof(BackgroundChanger), new UIPropertyMetadata(false, OnStatusChange));

    #endregion

    private static void OnStatusChange(DependencyObject obj,  DependencyPropertyChangedEventArgs e) 
    {
        var element = obj as Control;
        if (element != null)
        {
            if ((bool)e.NewValue)
                element.Background = Brushes.LimeGreen;
            else
                element.Background = default(Brush);
        }
    }
}

我这样使用它:

<Label CustomControls:BackgroundChanger.Status="{Binding test}" />

效果很好。当在 View 模型中设置相应的变量 test 时,背景颜色将更改为 LimeGreen

我的问题:

颜色LimeGreen是硬编码的。我也想在 XAML 中设置该颜色(以及默认颜色)。这样我就可以决定背景在哪两种颜色之间切换。我该怎么做?

最佳答案

您可以拥有多个附加属性。访问它们很容易,有静态 Get..Set.. 方法,您可以向其中提供 DependencyObject 来附加您想要的属性值操作。

public class BackgroundChanger : DependencyObject
{
    // make property Brush Background
    // type "propdp", press "tab" and complete filling

    private static void OnStatusChange(DependencyObject obj,  DependencyPropertyChangedEventArgs e) 
    {
        var element = obj as Control;
        if (element != null)
        {
            if ((bool)e.NewValue)
                element.Background = GetBrush(obj); // getting another attached property value
            else
                element.Background = default(Brush);
        }
    }
}

在 xaml 中它看起来像

<Label CustomControls:BackgroundChanger.Status="{Binding test}"
    CustomControls:BackgroundChanger.Background="Red"/>

关于c# - WPF 更改具有附加属性的控件的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26425771/

相关文章:

c# - 从具有指定长度的特定索引获取数组值

c# - 将 Autofac 与 ASP.Net Core 3.1 通用主机 "Worker Service"应用程序一起使用

wpf - 使用自定义面板问题将附加属性绑定(bind)到 ItemsControl 中的项目

wpf - 依赖属性 - 如何添加所有者以使其充当附加属性?

wpf - 直接设置绑定(bind)值

javascript - javascript对html进行更改后如何获取html源(无需浏览器)

c# - 为什么处理排序的数组比处理未排序的数组慢?

wpf - 根据组合框选择使按钮可见

wpf - 在 WPF ListView 中选择项目时,更新其他控件以查看详细信息

c# - 使用 .Net 4.0 从 Lock() 中调用 UI 线程上的方法