2015-11-02 48 views
0

我有一个Style下面的代码TreeViewItems在资源文件:WPF结合图片

<Setter Property="HeaderTemplate"> 
    <Setter.Value> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Image Name="img" 
        Width="20" 
        Height="20" 
        Stretch="Fill" 
        Source=""/> 
       <TextBlock Text="{Binding}" Margin="5,0" /> 
      </StackPanel> 
     </DataTemplate> 
    </Setter.Value> 
</Setter> 

我怎么现在可以为在代码中TreeViewItem图像/源?

+0

是MVVM的应用?或窗口后面的代码? – StepUp

+0

我的意思是一个wpf应用程序背后的C#代码。 – MyNameIsHans

+0

图像总是一样吗?还是取决于treeviewitem? – Jens

回答

0

XAML:

<Window x:Class="TreeViewWpfApplication.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
     <TreeView Name="treeView"> 
     </TreeView>   
    </Grid> 
</Window> 

后面的代码:

public partial class MainWindow : Window 
    { 
     public MainWindow() 
     { 
      InitializeComponent(); 
      CreateTree(); 
     } 

     private void CreateTree() 
     { 
      treeView.Items.Add(GetTreeView("text")); 
     } 

     private TreeViewItem GetTreeView(string text) 
     { 
      TreeViewItem newTreeViewItem = new TreeViewItem(); 

      // create stack panel 
      StackPanel stack = new StackPanel(); 
      stack.Orientation = Orientation.Horizontal; 

      // create Image 
      Image image = new Image(); 
      image.Source = new BitmapImage(new Uri(@"/Images/YourImage.png", UriKind.Relative)); 

      // Label 
      TextBlock lbl = new TextBlock(); 
      lbl.Text = text; 
      lbl.TextWrapping = TextWrapping.Wrap; 
      lbl.Width = 139; 

      // Add into stack 
      stack.Children.Add(image); 
      stack.Children.Add(lbl); 

      // assign stack to header 
      newTreeViewItem.Header = stack; 

      return newTreeViewItem; 
     } 
    } 
} 

注重的是image.Source = new BitmapImage(new Uri(@"/Images/YourImage.png", UriKind.Relative))其中 “/图片/” - 文件夹的名称。

+0

谢谢!但是,我怎样才能使项目可扩展?编辑:Nvm我只是没有添加一个子项目。感谢您的帮助:) – MyNameIsHans

+0

@MyNameIsHans你可以接受我的回复作为答案,如果它对你有帮助:)。 – StepUp

+0

谁回答了这个问题?它对我来说完全正常。 – MyNameIsHans