Reputation: 25
I have a list of objects and I'm trying to bind it to a TreeView in WPF:
private List<SlideIssue> slideIssuesList = new List<SlideIssue>();
Here the XAML:
<Grid Grid.Row="2">
<TreeView x:Name="mainTreeView" BorderThickness="0">
</TreeView>
</Grid>
And the binding attempt:
TreeViewItem item = new TreeViewItem();
item.HeaderTemplate = headerTemplate;
foreach (var issue in slideIssuesList)
{
if (slideNumber == issue.SlideNumber)
{
TreeViewItem child = new TreeViewItem();
child.ItemsSource = slideIssuesList;
child.HeaderTemplate = itemTemplate;
item.Items.Add(child);
}
}
item.IsExpanded = true;
mainTreeView.Items.Add(item);
At runtime, this is what I get:
I want to access the particular Properties of the "SlideIssue" Object. How do I do that?
Upvotes: 1
Views: 2299
Reputation: 169200
You could define a DataTemplate
for your SlideIssue
type and bind any element in the template to any of the class' public
properties:
<TreeView x:Name="mainTreeView" BorderThickness="0"
xmlns:local="clr-namespace:WpfApplication1">
<TreeView.Resources>
<DataTemplate DataType="{x:Type local:SlideIssue}">
<StackPanel>
<TextBlock Text="{Binding SlideNumber}" />
<TextBlock Text="{Binding SomeOtherPropertyOfSlideIssue}" />
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
Change "WpfApplication1" to the name of namespace
in which the SlideIssue
class is defined.
It kinda works. But I've build a complicated template in C# so i prefer creating it from there. I only have one problem: can you help me write this line of code to C#?
The easiest and preferred way to create a DataTemplate
programmatically is to use the XamlReader.Parse
method:
DataTemplate dataTemplate = System.Windows.Markup.XamlReader.Parse("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" xmlns:local=\"clr-namespace:WpfApplication1;assembly=WpfApplication1\" DataType=\"{x:Type local:SlideIssue}\"><StackPanel><TextBlock Text=\"{Binding SlideNumber}\" /><TextBlock Text=\"{Binding SomeOtherPropertyOfSlideIssue}\" /></StackPanel></DataTemplate>") as DataTemplate;
Just remember to replace "WpfApplication1" with the actual name of the namespace and assembly in which your SlideIssue
class is defined.
Upvotes: 1
Reputation: 71
You need to override ToString() method in the SlideIssue class. When you bind any object to control it call ToString() method to print data, if ToString() isn't overrided it print reference class name.
Upvotes: 1