簡體   English   中英

使用WPF和綁定單擊時更改按鈕背景顏色

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

我正在嘗試單擊時更改為按鈕的顏色。 它采用分配的初始顏色,但單擊后不會更新。 我附上我的代碼,讓我知道我要去哪里了。 我試圖實現以下帖子中提供的代碼

在此處輸入鏈接說明

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

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

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

最后是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();
        }
    }
}

您需要在BackgroundColorBtn1屬性上調用OnPropertyChanged,因為您正在更改私有支持變量,並且需要通知View。

您可以按以下方式修改MyAction方法

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

另外,您可以直接設置屬性而不是后備字段,這將調用OnPropertyChanged調用本身。

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

您還需要使用顏色畫筆轉換器。 按鈕的background屬性接受畫筆,而不接受顏色。 轉換器將允許您將所選的顏色轉換為畫筆。

您可以定義轉換器如下

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

然后,您可以將其用作

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

使用之前,請確保已在“資源”部分添加了以下內容

<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