简体   繁体   中英

How to bind an UI element to different object dynamically WPF c#

I have a question about how to binding an element with multiple different object dynamically.

So, consider this environment: I have a class Engine and two other classes classA and classB .

I have a MainWindow.xaml that is composed by multiple elements and Engine updating all of these, but there is an element that is bound with instruction performed by classA or classB .

How can I achieve that?

Until today, I had only one class so in

Engine : INotifyPropertyChanged

I had a property ClassA .

And in my

ClassA : INotifyPropertyChanged 

I had a property named InfoAboutPerfomedInstruction

In my xaml I have a textBox that has a text bound to Engine.ClassA.InfoAboutPerfomedInstruction

Should I have a generic class that inherits from classA and classB? There are a more elegant way to do this?

If I understand the question correctly then you want both ClassA and ClassB to be able to update the same property, correct? If so then I would have an interface that supports a callback for that property, so something like this:

public class IMyIterface
{
    event EventHandler<int> OnChanged;
}

ClassA and ClassB should both implement this interface, and invoke it when they want to change the value:

public class ClassA : IMyIterface
{
    public event EventHandler<int> OnChanged;

    public void SomethingChanged()
    {
        this.OnChanged?.Invoke(this, 42);
    }
}

// .. same for ClassB...

You then have some parent object that creates these, implements the value itself with INPC and subscribes to these events:

public class ParentViewModel
{
    private ClassA ClassA = new ClassA();
    private ClassB ClassB = new ClassB();

    public int MyValue ... // <- implements INPC

    public ParentViewModel()
    {
        this.ClassA.OnChanged += (s, e) => this.MyValue = e;
        this.ClassB.OnChanged += (s, e) => this.MyValue = e;
    }
}

This parent object is what your view binds to. The advantages of doing things like this are:

  1. the view doesn't know anything about ClassA or ClassB or the logic behind how they're updating the value
  2. you can easily put breakpoints throughout your logic code to ensure it's behaving correctly using the debugger
  3. you can unit-test it

Take this one step further and ClassA/ClassB are properties in ParentViewModel of type IMyIterface that get set via a dependency injection framework, but that's a topic for another post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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