繁体   English   中英

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

[英]Datatemplate in c# code-behind

我搜索一个选项,用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”一词)。 任何的想法?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM