4

我搜索一个选项以在 c# 代码中构建数据模板。我曾经使用过:

DataTemplate dt = new DataTemplate(typeof(TextBox));

        Binding bind = new Binding();
        bind.Path = new PropertyPath("Text");
        bind.Mode = BindingMode.TwoWay;

        FrameworkElementFactory txtElement = new FrameworkElementFactory(typeof(TextBox));
        txtElement.SetBinding(TextBox.TextProperty, bind);

        txtElement.SetValue(TextBox.TextProperty, "test");


        dt.VisualTree = txtElement;


        textBox1.Resources.Add(dt, null);

但它不起作用(它被放置在窗口的加载方法 - 所以我的文本框应该在窗口开始时显示单词“test”)。任何想法?

4

1 回答 1

8

每个元素都需要添加到当前的可视化树中。例如:

ListView parentElement; // For example a ListView

// First: create and add the data template to the parent control
DataTemplate dt = new DataTemplate(typeof(TextBox));
parentElement.ItemTemplate = dt;

// Second: create and add the text box to the data template
FrameworkElementFactory txtElement = 
    new FrameworkElementFactory(typeof(TextBox));
dt.VisualTree = txtElement;

// Create binding
Binding bind = new Binding();
bind.Path = new PropertyPath("Text");
bind.Mode = BindingMode.TwoWay;

// Third: set the binding in the text box
txtElement.SetBinding(TextBox.TextProperty, bind);
txtElement.SetValue(TextBox.TextProperty, "test");
于 2012-09-24T07:15:21.927 回答