我搜索一个选项,用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);
Run Code Online (Sandbox Code Playgroud)
但它不起作用(它被放置在窗口的Loaded-Method中 - 所以我的文本框应该在窗口开始时显示"test"一词).任何的想法?