Datatemplate dans c # code-behind

Je recherche une option pour construire un modèle de données en code c #. J’avais utilisé:

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

Mais cela ne fonctionne pas (il est placé dans la méthode Loaded de la fenêtre – mon champ de texte devrait donc afficher le mot “test” au début de la fenêtre). Une idée?

Chaque élément doit être ajouté à l’arborescence visuelle actuelle. Par exemple:

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