【问题标题】:How to set System.Windows.Controls.Image as static in XAML in a WPF Desktop Application如何在 WPF 桌面应用程序的 XAML 中将 System.Windows.Controls.Image 设置为静态
【发布时间】:2019-07-06 20:22:26
【问题描述】:

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

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

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

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

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;

这对我来说似乎是一种 hack,在我看来,在 WPF 中这样做会打败整个 XAML 部分(背后的代码太多)。

【问题讨论】:

    标签: c# wpf image static


    【解决方案1】:

    如果你的 MainWindow 中有一个命名的 Image 元素,比如

    <Image x:Name="image"/>
    

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

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

    【讨论】:

    • 是的,这是非常理想的,完全符合我的需要。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 2019-11-07
    • 2013-05-04
    • 2011-07-29
    相关资源
    最近更新 更多