簡體   English   中英

如何在WPF桌面應用程序的XAML中將System.Windows.Controls.Image設置為靜態

[英]How to set System.Windows.Controls.Image as static in XAML in a WPF Desktop Application

我需要將MainWindow.xaml中的System.Windows.Controls.Image設置為靜態對象,以便可以在運行時從靜態方法更改源。

我知道您可以對諸如TextBox之類的對象使用ContentControl,但這不適用於System.Windows.Controls.Image。

昨天我才剛剛了解ContentControl,所以我現在進入另一個我不了解的編碼領域。

應用程式

<Application.Resources>
    <Label x:Name="label1" x:Key="label1"/>
    <Style x:Key="labels" TargetType="{x:Type ContentControl}">
        <Setter Property="Height" Value="24" />
        <Setter Property="Foreground" Value="#B3B3B3" />
    </Style>
</Application.Resources>

MainWindow.xaml

<ContentControl Content="{StaticResource label1}" Style="{StaticResource labels}"/>

MainWindow.xaml.cs

var label1 = Application.Current.Resources["label1"] as Label;
            label1.Content = "This is label1";

我需要從靜態方法更改圖像源,但是我需要更優化的方法。

private static System.Windows.Controls.Image staticimage1 = new System.Windows.Controls.Image();

staticimage1 = image1;

在我看來,這似乎是一種黑客,而在WPF中這樣做似乎使整個XAML部分失敗(背后有太多代碼)。

如果您的MainWindow中有一個命名的Image元素,例如

<Image x:Name="image"/>

您可以通過靜態Application.Current屬性從靜態方法訪問它:

((MainWindow)Application.Current.MainWindow).image.Source
    = new BitmapImage(new Uri(...));

暫無
暫無

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

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