【问题标题】:How can I bind a background color in WPF/XAML?如何在 WPF/XAML 中绑定背景颜色?
【发布时间】:2010-12-30 01:09:28
【问题描述】:

我必须更改以下代码以使背景变为红色,我尝试的两种方法均无效:


(来源:deviantsart.com

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>

代码隐藏:

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

    }
}

更新 1:

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


(来源:deviantsart.com

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>

代码隐藏:

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

    }
}

【问题讨论】:

标签: c# wpf xaml binding background


【解决方案1】:

重要:

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

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

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

System.Windows.Media.Colors.Aquamarine(类名是Colors)Color)

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

【讨论】:

  • 请注意System.Windows.Media.Colors 命名空间返回一个System.Windows.Media.Color 没有s
  • “确保您使用的是 System.Windows.Media.Brush 而不是 System.Drawing.Brush”这句话很有帮助
【解决方案2】:

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

Background = new SolidColorBrush(Colors.Red);

【讨论】:

  • 这似乎对我不起作用,我在上面发布了代码(更新 1)
  • 确保使用 System.Windows.Media 中的 SolidColorBrush 而不是 System.Drawing 中的 SolidBrush
  • 我知道我参加聚会有点晚了,但它是 Colors.Red,而不是 Color.Red。在我找到答案之前,您的答案有点困惑。
  • 在这种情况下最简单的变体是使用预定义的纯色画笔 Background = Brushes.Red //System.Windows.Media
  • 一个令人沮丧且容易错过的概念:&lt;TextBlock Background="{Binding TheBackground}"/&gt; 被问及需要 System.Windows.Media.SolidColorBrush 命名空间。如果您需要不透明度并使用 &lt;SolidColorBrush Color="{Binding TheBackground}" Opacity="{Binding TheOpacity}"/>,则需要 System.Windows.Media.Color 命名空间。这个答案显示了如何在两者之间进行转换。
【解决方案3】:

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

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;
        }
    }

【讨论】:

  • 从使用原始颜色更改为使用 SolidColorBrush 为我解决了这个问题。谢谢
【解决方案4】:

我想通了,这只是一个命名冲突问题:如果您使用 TheBackground 而不是 Background,它的工作原理与发布在第一个例子。属性 Background 干扰了 Window 属性背景。

【讨论】:

    【解决方案5】:

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

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

    【讨论】:

    【解决方案6】:

    xaml 代码:

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

    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;
    
        }
    

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

    【讨论】:

    • 在这种情况下最简单的变体是使用预定义的纯色画笔 Background = Brushes.Red //System.Windows.Media
    【解决方案7】:

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

    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
    
            //...//
    }
    

    然后您可以像这样使用绑定到 SolidColorBrush:

    public Window1()
    {
        InitializeComponent();
        DataContext = this;
    
        Background = Colors.Red;
        Message = "This is the title, the background should be " + Background.toString() + ".";
    
    }
    

    不是 100% 确定 Color-Object 上的 .toString() 方法。它可能会告诉你它是一个 Color-Class,但你会弄明白的 ;)

    【讨论】:

      【解决方案8】:

      你仍然可以使用“Background”作为属性名,只要你给你的窗口一个名字并且在Binding的“Source”上使用这个名字。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-27
        • 1970-01-01
        • 2011-05-07
        • 1970-01-01
        • 1970-01-01
        • 2020-05-22
        相关资源
        最近更新 更多