Search code examples
wpfmvvmtreeviewbinddatatemplate

Cannot set Foreground Color to a TreeView DataTemplate TextBlock (MVVM)


I bind a TreeNode item list to a tree view. I am not able to bind to the DataTemplate TextBlock the Foreground color.

Initally I tought it is a binding problem, so I tried to give it a color manually, namely Foreground="Red" but I figured even like this it does not change my text color.

xaml:

 <TreeView  ItemsSource="{Binding TreeViewNodesPLCCode}" >
         <TreeView.ItemTemplate>
              <DataTemplate>
                  <Grid>
                     <TextBlock Text="{Binding Name}" Foreground="{Binding Path=MachineObject.Color}"/>
                     </Grid>
               </DataTemplate>
          </TreeView.ItemTemplate>
   </TreeView>

Code:

TreeViewNodesPLCCode=new ObservableCollection<TreeNode>()

 public class TreeNode: TreeViewItem
    {
        public string Name{ get; set; }
        public Machine MachineObject { get; set; }
    }
  public class Machine
    {
        public Int32 ID { get; set; }
        public Brush Color { get; set; }
    }

Solution

  • When I try your code, I get the following output in Visual Studio:

    ItemTemplate and ItemTemplateSelector are ignored for items already of the ItemsControl's container type; Type='TreeNode'

    This means that you are adding in the TreeView items that can be added directly without an DataTemplate.

    DataTemplate are made to visualize data objects (i.e. your business objects). TreeViewItem already have a DataTemplate.

    To solve your issue, remove the inheritance to TreeViewItem for your class TreeNode:

    public class TreeNode
        {
            public string Name{ get; set; }
            public Machine MachineObject { get; set; }
        }