C# 如何在 WPF/XAML 中绑定背景颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1962149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:13:42  来源:igfitidea点击:

How can I bind a background color in WPF/XAML?

c#wpfxamlbindingbackground

提问by Edward Tanguay

What do I have to change to the following code so that the background is red, neither of the 2 ways I tried worked:

我必须对以下代码进行什么更改才能使背景为红色,我尝试过的两种方法都不起作用:

alt text
(source: deviantsart.com)

替代文字
(来源:deviansart.com

XAML:

XAML:

<Window x:Class="TestBackground88238.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>

        <TextBlock Text="{Binding Message}" Background="{Binding Background}"/>

        <TextBlock Text="{Binding Message}">
            <TextBlock.Background>
                <SolidColorBrush Color="{Binding Background}"/>
            </TextBlock.Background>
        </TextBlock>

    </StackPanel>
</Window>

Code Behind:

背后的代码:

using System.Windows;
using System.ComponentModel;

namespace TestBackground88238
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {

        #region ViewModelProperty: Background
        private string _background;
        public string Background
        {
            get
            {
                return _background;
            }

            set
            {
                _background = value;
                OnPropertyChanged("Background");
            }
        }
        #endregion

        #region ViewModelProperty: Message
        private string _message;
        public string Message
        {
            get
            {
                return _message;
            }

            set
            {
                _message = value;
                OnPropertyChanged("Message");
            }
        }
        #endregion



        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            Background = "Red";
            Message = "This is the title, the background should be " + Background + ".";

        }

        #region INotifiedProperty Block
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }
}

Update 1:

更新 1:

I tried Aviad's answer which didn't seem to work. I can do this manually with x:Name as shown here but I want to be able to bind the color to a INotifyPropertyChanged property, how can I do this?

我尝试了 Aviad 的答案,但似乎没有用。我可以使用 x:Name 手动执行此操作,如下所示,但我希望能够将颜色绑定到 INotifyPropertyChanged 属性,我该怎么做?

alt text
(source: deviantsart.com)

替代文字
(来源:deviansart.com

XAML:

XAML:

<Window x:Class="TestBackground88238.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>

        <TextBlock Text="{Binding Message}" Background="{Binding Background}"/>

        <TextBlock x:Name="Message2" Text="This one is manually orange."/>

    </StackPanel>
</Window>

Code Behind:

背后的代码:

using System.Windows;
using System.ComponentModel;
using System.Windows.Media;

namespace TestBackground88238
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {

        #region ViewModelProperty: Background
        private Brush _background;
        public Brush Background
        {
            get
            {
                return _background;
            }

            set
            {
                _background = value;
                OnPropertyChanged("Background");
            }
        }
        #endregion

        #region ViewModelProperty: Message
        private string _message;
        public string Message
        {
            get
            {
                return _message;
            }

            set
            {
                _message = value;
                OnPropertyChanged("Message");
            }
        }
        #endregion

        public Window1()
        {
            InitializeComponent();
            DataContext = this;

            Background = new SolidColorBrush(Colors.Red);
            Message = "This is the title, the background should be " + Background + ".";

            Message2.Background = new SolidColorBrush(Colors.Orange);

        }

        #region INotifiedProperty Block
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

    }
}

回答by Aviad P.

The Backgroundproperty expects a Brushobject, not a string. Change the type of the property to Brushand initialize it thus:

Background属性需要一个Brush对象,而不是一个字符串。将属性的类型更改为Brush并对其进行初始化:

Background = new SolidColorBrush(Colors.Red);

回答by Edward Tanguay

I figured this out, it was just a naming conflict issue: if you use TheBackgroundinstead of Backgroundit works as posted in the first example. The property Background was interfering with the Window property background.

我想通了,这只是一个命名冲突问题:如果您使用TheBackground而不是Background,它会像第一个示例中发布的那样工作。属性背景干扰了窗口属性背景。

回答by Oliver Hanappi

I recommend reading the following blog post about debugging data binding: http://beacosta.com/blog/?p=52

我建议阅读以下有关调试数据绑定的博客文章:http: //beacosta.com/blog/?p=52

And for this concrete issue: If you look at the compiler warnings, you will notice that you property has been hiding the Window.Background property (or Control or whatever class the property defines).

对于这个具体问题:如果您查看编译器警告,您会注意到您的属性一直隐藏 Window.Background 属性(或 Control 或该属性定义的任何类)。

回答by Gus Cavalcanti

You can still use "Background" as the property name, as long as you give your window a name and use this name on the "Source" of the Binding.

您仍然可以使用“背景”作为属性名称,只要您为窗口命名并在绑定的“源”上使用此名称即可。

回答by Simon_Weaver

Important:

重要的:

Make sure you're using System.Windows.Media.Brushand not System.Drawing.Brush

确保您正在使用System.Windows.Media.Brush而不是System.Drawing.Brush

They're not compatible and you'll get binding errors.

它们不兼容,您会收到绑定错误。

The color enumeration you need to use is also different

需要使用的颜色枚举也不同

System.Windows.Media.Colors.Aquamarine (class name is Colors) <--- use this one System.Drawing.Color.Aquamarine (class name is Color)

If in doubt use Snoopand inspect the element's background property to look for binding errors - or just look in your debug log.

如果有疑问,请使用Snoop并检查元素的背景属性以查找绑定错误 - 或者仅查看您的调试日志。

回答by Andrzej Gis

Here you've got a copy-paste code:

在这里你有一个复制粘贴代码:

class NameToBackgroundConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if(value.ToString() == "System")
            {
                return new SolidColorBrush(System.Windows.Media.Colors.Aqua);
            }else
            {
                return new SolidColorBrush(System.Windows.Media.Colors.Blue);
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }

回答by Eranda

The xaml code:

xaml 代码:

<Grid x:Name="Message2">
   <TextBlock Text="This one is manually orange."/>
</Grid>

The c# code:

C#代码:

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        CreateNewColorBrush();
    }

    private void CreateNewColorBrush()
    {

        SolidColorBrush my_brush = new SolidColorBrush(Color.FromArgb(255, 255, 215, 0));
        Message2.Background = my_brush;

    }

This one works in windows 8 store app. Try and see. Good luck !

这个适用于 Windows 8 商店应用程序。试试看。祝你好运 !

回答by thewhiteambit

You assigned a string "Red". Your Background property should be of type Color:

您分配了一个字符串“红色”。你的背景属性应该是颜色类型:

using System.Windows;
using System.ComponentModel;

namespace TestBackground88238
{
    public partial class Window1 : Window, INotifyPropertyChanged
    {

        #region ViewModelProperty: Background
        private Color _background;
        public Color Background
        {
            get
            {
                return _background;
            }

            set
            {
                _background = value;
                OnPropertyChanged("Background");
            }
        }
        #endregion

        //...//
}

Then you can use the binding to the SolidColorBrush like this:

然后你可以像这样使用 SolidColorBrush 的绑定:

public Window1()
{
    InitializeComponent();
    DataContext = this;

    Background = Colors.Red;
    Message = "This is the title, the background should be " + Background.toString() + ".";

}

not 100% sure about the .toString() method on Color-Object. It might tell you it is a Color-Class, but you will figur this out ;)

不是 100% 确定 Color-Object 上的 .toString() 方法。它可能会告诉你它是一个颜色等级,但你会弄清楚的 ;)