I have a scenario, where a treeview changes its data template and data binding definition dynamically. I created a treeview in XAML like this:
<TreeView x:Name="BimTreeView">
</TreeView>
I didn't defined the data template and binding definition in XAML. Because the data template and binding definition must have to be changed by user's preference.
I tried the following C# code that I found here to create the data template definition dynamically. However, looking at the following code, I couldn't figure out how to change data binding definition via C# code.
private DataTemplate GetHeaderTemplate()
{
//create the data template
DataTemplate dataTemplate = new DataTemplate();
//create stack pane;
FrameworkElementFactory stackPanel = new FrameworkElementFactory(typeof(StackPanel));
stackPanel.Name = "parentStackpanel";
stackPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
// Create check box
FrameworkElementFactory checkBox = new FrameworkElementFactory(typeof(CheckBox));
checkBox.Name = "chk";
checkBox.SetValue(CheckBox.NameProperty, "chk");
checkBox.SetValue(CheckBox.TagProperty, new Binding());
checkBox.SetValue(CheckBox.MarginProperty, new Thickness(2));
checkBox.SetValue(CheckBox.TagProperty, new Binding() { Path = new PropertyPath("Name") });
stackPanel.AppendChild(checkBox);
// Create Image
FrameworkElementFactory image = new FrameworkElementFactory(typeof(Image));
image.SetValue(Image.MarginProperty, new Thickness(2));
image.SetBinding(Image.SourceProperty, new Binding() { Path = new PropertyPath("ImageUrl") });
stackPanel.AppendChild(image);
// create text
FrameworkElementFactory label = new FrameworkElementFactory(typeof(TextBlock));
label.SetBinding(TextBlock.TextProperty, new Binding() { Path = new PropertyPath("Name") });
label.SetValue(TextBlock.ToolTipProperty, new Binding());
stackPanel.AppendChild(label);
//set the visual tree of the data template
dataTemplate.VisualTree = stackPanel;
return dataTemplate;
}
I would really appreciate if someone could explain how can I change the data template and bind treeview hierarchical data in code behind C#.
Thank you!!
TreeViewItem. You can just modify that instance.Because the data template and binding definition must have to be changed by user's preference.Can you share more light on this?BindingOperations.ClearBindingand access yourlabelorimageusingFindName. Howerver I suggest you making a ViewModel instead.