【发布时间】: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 部分(背后的代码太多)。
【问题讨论】: