绑定到动态创建的控件

时间:2012-01-26 16:54:53

标签: wpf binding

我无法将值绑定到动态创建的控件。当用户加载自定义文件时,该文件将具有未知数量的参数。参数有一个Group属性,在分组时会动态地将tabItem添加到tabControl。然后我循环遍历参数并添加一个标签,现在,一个文本框到标签内的网格。虽然我打算根据文件类型使用不同的控件。我想将参数Value属性绑定到文本框。选项卡,标签和文本框添加正常,但没有值绑定

他是否到目前为止尚未重新考虑解决方案;

    myTab.Items.Clear();

    var args = viewModel.Arguments;
    var groups = args.GroupBy(arg => arg.Groups);

foreach (var group in groups)
{
    TabItemExt tab = new TabItemExt();
    tab.Header = group.Key;

    Grid grid = new Grid();

    grid.ColumnDefinitions.Add(new ColumnDefinition());
    grid.ColumnDefinitions.Add(new ColumnDefinition());

    int count = 0;
    foreach (var argument in group)
    {
        RowDefinition newRow = new RowDefinition();
        grid.RowDefinitions.Insert(count, newRow);

        LabelTextBlock label = new LabelTextBlock();
        label.Text = argument.DisplayName;

        Grid.SetRow(label, count);
        Grid.SetColumn(label, 0);

        TextBox textBox = new TextBox();
        var binding = new Binding();
        binding.Source = viewModel.Arguments[argument.Name];
        //binding.Source = argument
        binding.Path = new PropertyPath("Value");

        textBox.SetBinding(TextBlock.TextProperty, binding);

        Grid.SetRow(textBox, count);
        Grid.SetColumn(textBox, 1);

        grid.Children.Add(label);
        grid.Children.Add(textBox);
        count += 1; 
    }

    tab.Content = grid;
    myTab.Items.Add(tab);    
}

1 个答案:

答案 0 :(得分:1)

textBox.SetBinding(TextBlock.TextProperty, binding);

应该是

textBox.SetBinding(TextBox.TextProperty, binding);

稍微依赖智能感知。