Controlling binding to two properties

Using MVVM pattern and WPF, I would like to bind my controls to two properties. Let's say I have a label bound to a property on VM1 and I would like to bind it to a property on VM2 as well in order to send the resulting value from VM1 to VM2.

I could use messenger for multiple Tuple Class elements as well, but I was wondering if there is another solution for this. MultiBinding? but then I need a ValueConverter.

Thanks for any suggestions.

+3


source to share


2 answers


Since the View Model is an abstraction of a View that exposes public properties and commands, it doesn't make much sense to represent the two View Models as you explained. It will be more rational if there is a class as the view model of your view VM

that has two properties of type VM1

and VM2

. Then the binding will be on VM.VM1.YourText

and you can notify VM2

via events like this:

in VM1:

    public event EventHandler<EventArgs> ValueChanged;

    string _yourText;
    public string YourText
    {
        get
        {
            return _yourText;
        }
        set
        {
            _yourText= value;
            if (ValueChanged != null)
                ValueChanged(_yourText, new EventArgs());
        }
    }

      



In VM:

    public VM1 Vm1 {get; set;}
    public VM2 Vm2 {get; set;}

    public VM()
    {
        InitializeComponent();
        Vm1 = new VM1();
        Vm2 = new VM2();
        Vm1.ValueChanged += Item_ValueChanged;
        DataContext = this;
    }

    void Item_ValueChanged(object sender, EventArgs e)
    {
        VM2.YourAnotherText = sender.ToString();
    }

      

+1


source


If 2 properties are connected, it is usually possible to use INotifyPropertyChanged to notify 2 or more properties change if on the same ViewModel.

I understand that you also want to notify the View connected to the ViewModel to change the property to another ViewModel. This is usually done by allowing the ViewModels to communicate.



If this is one rare case, using the message bus for this may be overkill. Generally, keeping a reference to each view model and changing properties outside should be okay. To maintain separation of concerns, you can create an interface on one or both models and reference that interface instead of a specific type.

Keeping a single binding between the control and the property makes it easy and straightforward to understand, and you have to worry about this property handling all changes to / from other virtual machines.

+1


source







All Articles