0
votes

sorry, I am pretty new in WPF and I think it's pretty easy, but I have no idea right now.

I have a DataTemplate which I want to use as a TreeViewItem-Header (I've copied the template from somewhere else, so I am not really sure what it does at the TextBlock part):

<Window.Resources>
    <DataTemplate x:Key="WI_Bug">
        <DockPanel>
            <Image Source="images\bug-icon.png" Height="16" Width="16"/>
            <TextBlock Text ="{Binding Path=Name}"/>
        </DockPanel>
    </DataTemplate>
</Window.Resources>

Now I create a new item in C# code:

TreeViewItem tvi = new TreeViewItem();
tvi.HeaderTemplate = (DataTemplate) this.Resources["WI_Bug"];
tvi.Header = "I am a bug";
treeView1.Items.Add(tvi);

My problem: The icon, that I've set in the datatemplate is shown, but the header text itself doesn't appear anymore. How can I fill the TextBlock from the DataTemplate in the C#-code?

2

2 Answers

1
votes

The DataContext in the HeaderTemplate is the Header, the Header is a string, it has no Name property (where is that supposed to be anyway?).

If you just have a string you want a binding directly to the DataContext: {Binding}

You also might want to read up on debugging data bindings, it helps.

0
votes

try this. and you should check your output window for binding errors, because that happens with your example

<Window.Resources>
 <DataTemplate x:Key="WI_Bug">
    <DockPanel>
        <Image Source="images\bug-icon.png" Height="16" Width="16"/>
        <TextBlock Text ="{Binding Path=.}"/>
    </DockPanel>
 </DataTemplate>
</Window.Resources>