How to interact with user interface elements when using MVVM / MVVMLight in a WPF application

According to my code below, I want to be able to change the background color Button 2when clicked Button 1.

Xaml file

    <Grid>
        <Button x:Name="Button1" 
                Content="Button 1" 
                Command="{Binding Button1Command}"/>

        <Button x:Name="Button2" 
                Content="Button 2"/>
    </Grid>

ViewModel File

public class MyViewModel : ViewModelBase
{
    public ICommand Button1Command{get;private set;}

    public MyViewModel(){
        Button1Command = new RelayCommand(() => button1_Click());
    }

    private void button1_Click()
    {
        Console.WriteLine("Button 1 clicked");

        // how can I change the background color of Button 2 here
        this.Dispatcher.Invoke(() => {
           Button2.Background = Brushes.Red;
        });
    }
}
+4
source share
2 answers

In addition to what was mentioned in pm_2, you can use the MVVMLight class Messenger. The VM can send a message that is received in the view to change the background.

public class ChangeBackgroundMessage
{
    public Brush TheColor { get; set; } 
} 

And then in your virtual machine:

Button1Command = new RelayCommand(() => ExecuteButtonCommand());

....

private void ExecuteButtonCommand()
{
    Messenger.Default.Send<ChangeBackgroundMessage>(new ChangeBackgroundMessage { TheColor = Brushes.Red } );
} 

and in your view:

public partial class MyView : UserControl
{
    public MyView()
    {
         InitializeComponent();
         Messenger.Default.Register<ChangeBackgroundMessage>(this, m => ReceiveChangeBackgroundMessage(m);
    } 

    private void ReceiveChangeBackgroundMessage(ChangeBackgroundMessage m)
    {
          // If you need to ensure this executes only on UI thread, use the
          // DispatcherHelper class

          DispatcherHelper.CheckBeginInvokeOnUI(() => button2.Background = m.TheColor);
    }

}

Another alternative is to have a "view service" that View registers with it the ViewModel. For instance:

public interface IMySpecificViewService
{ 
    void ChangeButtonColor(Brush color);
} 

In VM:

public IMySpecificViewService ViewService { get; set; } 

and in view

public partial class MyView : UserControl, IMySpecificViewService
...
public MyView()
{ 
    var vm = (MyViewModel)this.DataContext;
    vm.ViewService = (IMySpecificViewService)this;
} 

public void ChangeButtonColor(Brush color)
{
    Button2.Background = color;
}  

which can be called in your VM command handler:

private void ExecuteButtonCommand()
{
    ViewService?.ChangeButtonColor(Brushes.Red);
} 

, , ( ), .

+3

, spring - , Button2 viewmodel. ; , MVVM, .

, Button2, , Button1, , Button1; ( ViewModel) ( ).

, 1, button1_click, .

, .

+3

Source: https://habr.com/ru/post/1688420/


All Articles