[英]Dynamic two way binding to dynamic elements in wpf
我正在开发一个模块化应用程序,该应用程序将具有可能带有或不带有参数的过程。 将参数加载到每个过程,执行目标是要求用户输入所有必需的参数,然后执行一些额外的工作。
我已经设法加载了所有内容,并且一切正常,但是我不知道如何为每个参数值进行动态绑定。
我已经制作了一个演示应用程序来对此进行测试,尽管我花了点时间弄弄了它,但似乎仍然无法使它正常工作,我也不知道缺少了什么。
这是演示应用程序的代码,它是实际应用程序的简化版本,但是概念几乎相同:
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);
}
}
您已经将绑定的Source
对象和该对象的source属性的Path
混淆了。
它看起来应该像这样:
var myBinding = new Binding("Value");
myBinding.Source = x;
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
要么
var myBinding = new Binding
{
Path = new PropertyPath("Value"),
Source = x,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
txt.SetBinding(TextBox.TextProperty, myBinding);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.