Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatemplate in c# code-behind

I search an option to build a datatemplate in c# code. I had 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 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?

like image 930
user1565467 Avatar asked Feb 19 '23 01:02

user1565467


1 Answers

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");
like image 199
akton Avatar answered Feb 27 '23 02:02

akton