[英]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.