如何以编程方式替换TreeViewItem的图标?

时间:2012-03-01 11:27:20

标签: c# wpf xaml

在我目前的项目中,我有一个WPF TreeView并添加了这样的项目:

<TreeViewItem Name="treeViewItem6" IsEnabled="False">
  <TreeViewItem.Header>
    <StackPanel Orientation="Horizontal">
        <Image Height="16" Source="Images/16x16_green_lamp.png" Width="16" />
        <TextBlock Margin="5,0" Text="Status: Connected" />
    </StackPanel>
  </TreeViewItem.Header>
</TreeViewItem>

我想在C#代码中替换一个图标以及TextBlock的文本,使其看起来像这样:

enter image description here

是否有一种简单的方法可以以编程方式替换TreeViewItem的图标和文本,还是必须遍历整个子项目树? (不幸的是,我是WPF新手,而且我更习惯于旧的WinForms)

3 个答案:

答案 0 :(得分:1)

要更改图像的来源和文本块的文本,您可以为控件指定如下名称:

<Image Name="imgIcon" Height="16" Source="Images/16x16_green_lamp.png" Width="16" />
<TextBlock Name="tbStatus" Margin="5,0" Text="Status: Connected" />

这样,您可以通过编程方式更改要更改的属性,如下所示:

Image img = FindResource("red") as Image;
if (img != null) imgIcon.Source = img.Source;

tbStatus.Text = "Status: Disconnected";

要查找“绿色”和“红色”资源,您可以将它们添加到XAML中,如下所示:

<Window.Resources>
    <Image x:Key="green" Source="Images/16x16_green_lamp.png" />
    <Image x:Key="red" Source="Images/16x16_red_lamp.png" />
</Window.Resources>

当然,你需要额外的逻辑来确定状态,但这会让你开始。

答案 1 :(得分:1)

您可以将图像源绑定到ViewModel中的字符串属性,而不是硬编码图像的路径。 string属性需要表示要显示的图像的uri。更改字符串属性(并触发OnPropertyChanged事件)后,UI将自动更改图像。 WPF有一个用于图像的内置转换器,因此您不必过于担心。以下是绑定的外观:

<Image Source="{Binding ImageSource}" />

其中ItemSource是视图模型中的字符串属性。

希望有所帮助。

答案 2 :(得分:1)

如何生成树?那里有数据绑定吗? 如果树是手动构造的,为什么不简单地给要更改的元素命名,然后在代码中引用这些元素:

<TreeViewItem Name="treeViewItem6" IsEnabled="False">
    <TreeViewItem.Header>
        <StackPanel Orientation="Horizontal">
            <Image x:Name="StatusImage" Height="16" Source="Images/16x16_green_lamp.png" Width="16" />
            <TextBlock x:Name="StatusText" Margin="5,0" Text="Status: Connected" />
        </StackPanel>
    </TreeViewItem.Header>
</TreeViewItem>

然后,在C#代码中:

...
this.StatusImage.Source="...";  // a new ima
this.StatusText.Text = "....;

对于图像源,您需要生成它(文本不够):     新的BitmapSource(新的Uri(“图像uri”))

你应该构建一次并缓存它。