简体   繁体   English

使用WPF和绑定单击时更改按钮背景颜色

[英]Change Button background color when clicked using WPF and binding

I am trying to change to color of button when clicked. 我正在尝试单击时更改为按钮的颜色。 It is taking the initial color assigned but not updating when clicked. 它采用分配的初始颜色,但单击后不会更新。 I attaching my code, let me know where I am going wrong. 我附上我的代码,让我知道我要去哪里了。 I tried to implement the code provided in the following post 我试图实现以下帖子中提供的代码

enter link description here 在此处输入链接说明

MainWindow.xaml snippet MainWindow.xaml代码段

<Window.Resources>
    <viewModels:MainWindowViewModel x:Key="MainViewModel"/>
</Window.Resources>

<Border Padding="20">
    <StackPanel DataContext="{Binding Source={StaticResource MainViewModel}}">
        <Button Content="Button1" Margin="10 10 10 10" Command="{Binding ClickCommand, Mode=OneWay}" Background="{Binding BackgroundColorBtn1}"/>
        <Button Content="Button2 " Margin="10 10 10 10"></Button>
    </StackPanel>
</Border>

</Window>

MainWindow.xaml.cs MainWindow.xaml.cs

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new MainWindowViewModel();
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            var desktopWorkingArea = System.Windows.SystemParameters.WorkArea;
            this.Left = desktopWorkingArea.Right - this.Width;
            this.Top = desktopWorkingArea.Bottom - this.Height;
        }
    }

MainWindowViewModel.cs MainWindowViewModel.cs

namespace DockedPanel.ViewModels
{
    public class MainWindowViewModel:INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public MainWindowViewModel()
        {
            _canExecute = true;
        }
        private ICommand _clickCommand;
        public ICommand ClickCommand
        {
            get
            {
                return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), _canExecute));
            }
        }
        private bool _canExecute;
        public void MyAction()
        {
            _backgroundColorBtn1 = Colors.Blue;
        }

        private void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private Color _backgroundColorBtn1 =  Colors.White;
        public Color BackgroundColorBtn1
        {
            get { return _backgroundColorBtn1; }
            set
            {
                if (value == _backgroundColorBtn1)
                    return;

                _backgroundColorBtn1 = value;

                OnPropertyChanged(nameof(BackgroundColorBtn1));
            }
        }
    }
}

and finally CommandHandler 最后是CommandHandler

namespace DockedPanel.ViewModels.Command
{
    public class CommandHandler : ICommand
    {
        private Action _action;
        private bool _canExecute;
        public CommandHandler(Action action, bool canExecute)
        {
            _action = action;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            _action();
        }
    }
}

You need to call OnPropertyChanged on the BackgroundColorBtn1 property since you are changing the private backing variable, and the View needs to be notified. 您需要在BackgroundColorBtn1属性上调用OnPropertyChanged,因为您正在更改私有支持变量,并且需要通知View。

You can modify your MyAction method as following 您可以按以下方式修改MyAction方法

 public void MyAction()
 {
      _backgroundColorBtn1 = Colors.Blue;
      OnPropertyChanged(nameof(BackgroundColorBtn1));
 }

Alternatively, you could set the Property directly instead of backing field, which would invoke the OnPropertyChanged call itself. 另外,您可以直接设置属性而不是后备字段,这将调用OnPropertyChanged调用本身。

 public void MyAction()
 {
      BackgroundColorBtn1 = Colors.Blue;
 }

You would also need to use a Color To Brush Converter. 您还需要使用颜色画笔转换器。 The background property of button accepts Brush, not color. 按钮的background属性接受画笔,而不接受颜色。 The convertor would allow you to convert the chosen Color to Brush. 转换器将允许您将所选的颜色转换为画笔。

You can define the Converter as following 您可以定义转换器如下

public class ColorToSolidColorBrushValueConverter : IValueConverter 
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        if (value is Color)
            return new SolidColorBrush((Color)value);

        throw new InvalidOperationException("Unsupported type [" + value.GetType().Name + "], ColorToSolidColorBrushValueConverter.Convert()");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
   {
        throw new NotImplementedException();
    }
}

And then, you can use it as 然后,您可以将其用作

Background="{Binding BackgroundColorBtn1, Converter={StaticResource colorToSolidColorBrushConverter}}"

Please ensure you have added following to your Resource section before using it 使用之前,请确保已在“资源”部分添加了以下内容

<Window.Resources>
<ResourceDictionary>
        <myNameSpace:ColorToSolidColorBrushValueConverter  x:Key="colorToSolidColorBrushConverter"/>
</ResourceDictionary>
</Window.Resources>

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

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