this.Background 是指 Background 视图模型的属性提供了 ChangeColor 方法属于视图模型类。要更改窗口的背景,需要将其绑定到 Background 视图模型的属性并引发事件以告知UI更新。这需要您的视图模型来实现 INotifyPropertyChanged 事件:
this.Background
Background
ChangeColor
INotifyPropertyChanged
public class ViewModel : INotifyPropertyChanged { public RelayCommand ColorChangerCommand { get; set; } public TreeViewModel() //Constructor of the View Model { ColorChangerCommand = new RelayCommand(ChangeColor); } public void ChangeColor(object sender) { this.Background = (sender as TreeViewItem).Foreground; } private Brush background= Brushes.White; public Brush Background { get { return background; } set { Background = value; NotifyPropertyChanged(Background); } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
的 XAML: 强>
<Window .... Background="{Binding Background}" />
你还需要设置 DataContext 窗口的视图模型类的实例和绑定 Command 的财产 Hyperlink 像这样:
DataContext
Command
Hyperlink
<Hyperlink Command="{Binding DataContext.ColorChangerCommand, RelativeSource={RelativeSource AncestorType=Window}}" Foreground="{Binding Foreground}" TextDecorations="None">
不要通过ViewModel来做。 UI属于View。使用它的行为。
如果你绑定 ForwardedColor 对于任何其他UI控件,您将更改此控件的绑定属性,以便您可以在XAML中轻松管理它。
ForwardedColor
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" <TextBlock Text="Test" Foreground="Aquamarine"> <i:Interaction.Behaviors> <local:ForwardForegroundOnClick ForwardedColor="{Binding Background, RelativeSource={RelativeSource AncestorType=Window}, Mode=TwoWay}"/> </i:Interaction.Behaviors> </TextBlock> public class ForwardForegroundOnClick : Behavior<TextBlock> { public Brush ForwardedColor { get { return (Brush)GetValue(ForwardedColorProperty); } set { SetValue(ForwardedColorProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty ForwardedColorProperty = DependencyProperty.Register(nameof(ForwardedColor), typeof(Brush), typeof(ForwardForegroundOnClick), new PropertyMetadata(null)); protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonDown += AssociatedObject_MouseLeftButtonDown; } private void AssociatedObject_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { ForwardedColor = AssociatedObject.Foreground; } protected override void OnDetaching() { AssociatedObject.MouseLeftButtonDown -= AssociatedObject_MouseLeftButtonDown; base.OnDetaching(); } }