gpt4 book ai didi

c# - 动态双向绑定(bind)到 wpf 中的动态元素

转载 作者:行者123 更新时间:2023-11-30 20:30:20 27 4
gpt4 key购买 nike

我正在开发一个模块化应用程序,该应用程序将具有可能有参数也可能没有参数的过程。参数加载到每个过程,执行目标是要求用户输入所有必需的参数,然后它会做一些额外的工作。

我已经设法加载所有内容并且一切正常,但我不知道如何为每个参数值进行动态绑定(bind)。

我已经制作了一个演示应用程序来对此进行测试,尽管我已经摆弄了一段时间,但我似乎仍然无法让它工作,而且我不知道缺少什么。

下面是演示应用程序的代码,它是实际应用程序的简化版本,但概念几乎相同:

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);
}
}

最佳答案

您混淆了 Binding 的 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);

关于c# - 动态双向绑定(bind)到 wpf 中的动态元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44966496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com