在c#代码隐藏中进行数据模板化

时间:2012-09-24 06:59:57

标签: c# wpf datatemplate

我搜索一个选项,用c#代码构建一个datatemplate。 我用过:

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

但它不起作用(它被放置在窗口的Loaded-Method中 - 所以我的文本框应该在窗口开始时显示“test”一词)。有什么想法吗?

1 个答案:

答案 0 :(得分: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");