简体   繁体   中英

Dynamic two way binding to dynamic elements in wpf

I'm working on a modular application that will feature procedures that may or may not have parameters. Parameters are loaded to each procedure and on execution goal is to ask the user to input all required parameters then it does some extra work.

I've managed to load everything in and it all works fine, but I don't know how to make the dynamic binding for each of the parameters value.

I've made a demo application to test this, and even though I've fiddled with it for a bit I still can't seem to get it to work and I don't know what's missing.

Here's the code for the demo app that is a simplified version of the actual application, the concept is almost identical though:

public class TestBinding 
{
    public List<Val> Values {get;set;}

    public TestBinding()
    {
        Values = new List<Val>();
        Values.Add(new Val {Caption = "First", Value = String.Empty});
        Values.Add(new Val {Caption = "Second", Value = String.Empty});
        Values.Add(new Val {Caption = "Third", Value = String.Empty});
    }
}

public class Val 
{
    public string Caption {get;set;}
    public string Value {get;set;}
}

public TestBinding TB {get;set;}
public Window1()
{
    InitializeComponent();

    TB = new TestBinding();

    foreach(var x in TB.Values)
    {
        var txt = new TextBox() {Height = 25, Width = 150};

        var myBinding = new Binding("x.Value"); //???? Not sure about this
        myBinding.Source = x.Value;
        myBinding.Mode = BindingMode.TwoWay;
        myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        BindingOperations.SetBinding(txt, TextBox.TextProperty, myBinding);

        SPanel.Children.Add(txt);
    }

    var btn = new Button() {Height = 20, Width = 150, Content = "Show values"};

    btn.Click += new RoutedEventHandler(radioButton1_Click);
    SPanel.Children.Add(btn);
}

private void radioButton1_Click(object sender, RoutedEventArgs e)
{
    foreach(var x in TB.Values)
    {
        MessageBox.Show(x.Value);
    }
}

You have confused the Source object of the Binding and the Path to a source property of that object.

It should look like this:

var myBinding = new Binding("Value");
myBinding.Source = x;
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;

or

var myBinding = new Binding
{
    Path = new PropertyPath("Value"),
    Source = x,
    Mode = BindingMode.TwoWay,
    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};

txt.SetBinding(TextBox.TextProperty, myBinding);

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