How to insert my picture into my example?

xaml:

<TreeView x:Name="tw_tree" TreeViewItem.Expanded="TreeViewItem_Expanded" TreeViewItem.Selected="TreeViewItem_SelectedItem" > <TreeView.ItemTemplate> //здСсь происходит привязка //НуТно Π΄ΠΎΠ±Π°Π²ΠΈΡ‚ΡŒ ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ <HierarchicalDataTemplate ItemsSource="{Binding Path=collection_node}"> <TextBlock Text="{Binding name_}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 

But I need the picture to be determined by the level of my class Node.

  public class Node { public string name_ { get; set; } public int level { get; set; } public ObservableCollection<Node> collection_node { get; set; } public Node() { collection_node = new ObservableCollection<Node>(); } } 

So Node objects are added to the tree:

 tw_tree.ItemsSource = GLOBAL.node.collection_node; 
  • one
    And why do you create items manually, and not through the HierarchicalDataTemplate? - VladD
  • because I do not know how. thank. I will look. - codename0082016
  • Fixed item creation on tw_tree.ItemsSource = GLOBAL.node.collection_node; - codename0082016
  • And where is the picture in your Node? Or where do you want to take it from? - VladD
  • from the folder in the program. In Node it is not. - codename0082016

1 answer 1

The easiest way is probably this:

 <HierarchicalDataTemplate ItemsSource="{Binding Path=collection_node}"> <StackPanel Orientation="Horizontal"> <Image MaxHeight="30" MaxWidth="30" Source="{Binding level, Converter={StaticResource LevelToImageConverter}}"/> <TextBlock Text="{Binding name_}" /> </StackPanel> </HierarchicalDataTemplate> 

You will need another converter that you need to put into the page resources (you know how?). The converter itself looks something like this:

 public class LevelToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var level = (int)value; var uriString = ("pack://application:,,,/Images/tree" + level + ".png"; return BitmapFrame.Create(new Uri(uriString)); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementaedException(); } } 
  • System.Windows.Markup.XamlParseException Not Handled by Message: An unhandled exception of type "System.Windows.Markup.XamlParseException" in PresentationFramework.dll Additional information: "Providing a value for" System.Windows.Markup.StaticResourceHolder "caused an exception.": Line number "211" and the position in the string "33". - codename0082016
  • Source="{Binding level, Converter={StaticResource LevelToImageConverter}}"/> Failed to resolve LevelToImageConverter resource - codename0082016
  • after adding earned <local:LevelToImageConverter x:Key="LevelToImageConverter"/> - codename0082016
  • @ codename0082016: Yes, exactly. - VladD