【问题标题】:How do you set a Xaml defined, Window.Resource Image programmatically?如何以编程方式设置 Xaml 定义的 Window.Resource Image?
【发布时间】:2015-02-11 21:19:39
【问题描述】:

我有一个 xaml 文件,其中包含我在窗口中使用的一系列资源。具体来说,我有两个 Image 对象。我需要在 Window 的构造函数中设置这些图像,而不是对 URI 位置进行编码。我该怎么做?

我找了又找,我尝试设置图片.Source属性。没有任何效果。作为参考,以下是这些图像在我的 xaml 文件中的声明方式:

<Window.Resources>
    <Image x:Key="iUpdate" />
    <Image x:Key="iDelete" />
</Window.Resources>

下面是它们用于按钮内容的方式:

                <DataTemplate>
                    <DockPanel>
                        <Button Name="UpdateChange" Content="{StaticResource iUpdate}" Width="24" />
                        <Button Name="DeleteChange" Content="{StaticResource iDelete}" Width="24" />
                        <Label Content="{Binding name}" />
                    </DockPanel>
                </DataTemplate>

这是我设置图像来源的失败尝试。

        //In my constructor...
        // iUpdate is a property on the Window
        iUpdate = (Image)FindResource("iUpdate");
                    iUpdate = new Image();
        iUpdate.Source = ImageHelpers.ConvertBitmapToImageSource(Common.LoadImage("edit.ico"));

仅供参考,我无法在我的 xaml 文件中设置源代码,因为对 Common.LoadImage(...) 的调用是解析文件位置的特殊调用。这可能因用户而异,这就是帮助方法首先存在的原因。

【问题讨论】:

  • 为什么不绑定到两个视图模型属性?您将在 XAML 中创建 Image 控件作为 Button 的内容,并将其 Source 属性绑定到视图模型属性(或您的 MainWindow 类的属性,如果您愿意的话)。无论如何,将控件作为资源是一个坏主意。
  • @Clemens 我会调查的。这是我第一次尝试 WPF。这种方法可能会奏效。我该怎么做?

标签: c# wpf image xaml


【解决方案1】:

您可以在 MainWindow 类中声明并绑定两个属性,而不是使用 Image 控件作为资源。

public partial class MainWindow : Window
{
    public MainWindow()
    {
        UpdateImage = ImageHelpers.ConvertBitmapToImageSource(...);
        DeleteImage = ImageHelpers.ConvertBitmapToImageSource(...);

        InitializeComponent();
    }

    public ImageSource UpdateImage { get; set; }
    public ImageSource DeleteImage { get; set; }
}

您可以通过为窗口指定名称来绑定到这些属性

<Window ... x:Name="window">

并声明一个 ElementName 绑定:

<Button ...>
    <Button.Content>
        <Image Source="{Binding UpdateImage, ElementName=window}"/>
    </Button.Content>
</Button>

为了回答您的问题,您的问题是您在将新的 Image 实例分配给资源实例之后立即将其分配给 iUpdate 字段。你的代码应该是这样的:

iUpdate = (Image)Resources["iUpdate"];
iUpdate.Source = ImageHelpers.ConvertBitmapToImageSource(...);

【讨论】:

    猜你喜欢
    • 2011-09-07
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    • 2011-11-11
    相关资源
    最近更新 更多