Datatemplate in C # code-behind

I am looking for an option to build a datatemplate in C # code. I used:

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 does not work (it is placed in the Loaded-Method window - therefore, the word "test" should appear in my text box when the window starts). Any idea?

+4
source share
1 answer

Each item should be added to the current visual tree. For instance:

 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"); 
+8
source

Source: https://habr.com/ru/post/1435853/


All Articles