wpf c#代码隐藏中的数据模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12560249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 05:30:48  来源:igfitidea点击:

Datatemplate in c# code-behind

c#wpfdatatemplate

提问by user1565467

I search an option to build a datatemplate in c# code. I had used :

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

But it doesn't work (it is placed at the Loaded-Method of the window - so my textbox should show the word "test" at window start). Any idea?

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

回答by akton

Each element needs to be added to the current visual tree. For example:

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

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