簡體   English   中英

如何以編程方式替換TreeViewItem的圖標?

[英]How to programmatically replace the icon of a TreeViewItem?

在我當前的項目中,我有一個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的文本,以使其看起來像這樣:

在此處輸入圖片說明

有沒有一種簡便的方法可以以編程方式替換TreeViewItem的圖標以及文本,還是我必須遍歷整個子項樹? (不幸的是,我是WPF的新手,我更習慣於老式的WinForms)

要更改圖像的來源和文本塊的文本,可以為控件命名,如下所示:

<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>

當然,您將需要其他邏輯來確定狀態,但這將使您入門。

實際上,您可以將圖像源綁定到ViewModel中的字符串屬性,而不是對圖像的路徑進行硬編碼。 string屬性需要代表您要顯示的圖像的uri。 一旦更改了字符串屬性(並觸發OnPropertyChanged事件),您的UI就會自動更改圖像。 WPF具有用於圖像的內置轉換器,因此您不必為此擔心太多。 綁定的外觀如下所示:

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

其中ItemSource是視圖模型中的字符串屬性。

希望能有所幫助。

您如何生成樹? 那里有數據綁定嗎? 如果樹是手動構建的,為什么不簡單地給要更改的元素命名,然后在代碼中引用這些元素:

<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 = "....;

對於圖像源,您需要生成它(文本是不夠的):new BitmapSource(new Uri(“ image uri”))

您應該構造一次並緩存它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM