如何在运行时创建的文本框上设置数据绑定?

时间:2020-02-16 21:35:35

标签: c# wpf data-binding

通常,您需要像这样在XAML中设置数据绑定:

<Textbox Text="{Binding myDataBindingProperty}"/>

但是,我在WPF表单上有一个按钮,可以在运行时添加文本框。

    private void AddTextBox(object sender, RoutedEventArgs e)
    {
        TextBox myNewTextbox = new TextBox();
        grid.Children.Add(myNewTextbox);
    }

在添加文本框的同时,我希望能够设置数据绑定。但是,我不确定该怎么做。我尝试了一些变体,例如:

myNewTextbox.SetBinding(myDataBindingProperty);
myNewTextbox.Text = "{Binding myDataBindingProperty}";

以及我不会在这里重现的一些古怪的猜测!无论如何,用C#代码设置数据绑定的方式是什么?

我没有合适的绑定源,这比我想的要难得多。对于本示例,我正在考虑这种事情。如果您可以推荐一些对您有所帮助的改进。

    public MainWindow()
    {
        DataContext = new ViewModel();
        InitializeComponent();
    }

internal class ViewModel
    {
        public KeyValuePair<string, string> myDataBindingProperty
        {
            set { contentsOfMyNewTextboxes.Add(value.Key, value.Value); }
        }

        //Key = name of TextBox; Value = contents of text box
        private Dictionary<string, string> contentsOfMyNewTextboxes = new Dictionary<string, string>();
    }

1 个答案:

答案 0 :(得分:0)

使用代码进行绑定:

private void AddTextBox(object sender, RoutedEventArgs e)
{
    var myNewTextbox = new TextBox();

    var binding = new Binding
    {
        Path = new PropertyPath("myDataBindingProperty"),
        Mode = BindingMode.TwoWay
    };

    // Bind to the textbox
    myNewTextbox.SetBinding(TextBox.TextProperty, binding);

    grid.Children.Add(myNewTextbox);
}