如何从不同的命名空间更改图像源?

时间:2014-06-09 03:36:58

标签: c# wpf xaml namespaces

我对C#还不熟悉所以请原谅看起来像是一个新问题:我目前无法弄清楚如何从不同的命名空间更改MainWindow上的图像。这是我遇到的问题的简化版本:

MainWindow.xaml:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Image x:Name="imageToChange" Source="images/01.png" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" />
</Grid>

ChangeImage.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace Test.DiffNamespace
{
    class ChangeImage
    {
        Test.MainWindow.imageToChange.Source="images\02.png";  //This doesn't work
    }
}

说明显而易见,MainWindow正在测试中,而ChangeImage在Test.DiffNamespace下。我理想情况下这样做是为了工作而不必改变结构,但如果我尝试的是不可能的,我仍然可以解决方法。

2 个答案:

答案 0 :(得分:0)

假设您想要静态更新

的解决方案

你的类,带有指向图像的静态属性

class ChangeImage
{
    static ChangeImage()
    {
        Image = "images\02.png";
    }

    public static string Image { get; set; }
}

XAML,注意添加名称空间&#39;差异&#39;和图像源绑定

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:diff="clr-namespace:Test.DiffNamespace">
<Grid>
    <Image x:Name="imageToChange" 
           Source="{Binding Source={x:Static diff:ChangeImage.Image}}" 
           HorizontalAlignment="Left" 
           Height="100" 
           VerticalAlignment="Top" 
           Width="100" />
</Grid>

答案 1 :(得分:0)

如果将图像作为资源嵌入,则应使用以下代码

class ChangeImage
{
     // Test.MainWindow.imageToChange.Source="images\02.png";  //This doesn't work
    BitmapImage logo = new BitmapImage();
    logo.BeginInit();
    logo.UriSource = new Uri("pack://application:,,,/AssemblyName;component/Resources/logo.png");
    logo.EndInit();
    Test.MainWindow.imageToChange.Source = logo;
}
相关问题