首页 > 解决方案 > 如何在 WPF 桌面应用程序的 XAML 中将 System.Windows.Controls.Image 设置为静态

问题描述

我需要将 MainWindow.xaml 中的 System.Windows.Controls.Image 设置为静态对象,以便我可以在运行时从静态方法更改源。

我知道您可以将 ContentControl 用于 TextBox 等对象,但这不适用于 System.Windows.Controls.Image。

我昨天才刚刚了解 ContentControl,所以我现在进入了另一个我不太了解的编码领域。

应用程序.xaml

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

主窗口.xaml

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

主窗口.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 部分(背后的代码太多)。

标签: c#wpfimagestatic

解决方案


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

<Image x:Name="image"/>

Application.Current您可以通过静态属性从静态方法访问它:

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

推荐阅读