2014-06-09 80 views
0

我對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 
    } 
} 

不言自明的,主窗口下測試,而ChangeImage在Test.DiffNamespace下。我理想上喜歡這個工作而不需要改變結構,但如果我正在嘗試的是不可能的,我仍然可以接受解決方法。

回答

0

一個爲您解決假設你想更新靜態

類,具有靜態屬性指向圖像

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

    public static string Image { get; set; } 
} 

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" 
    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> 
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; 
} 
+0

請注意,BitmapImage有一個採用'Uri'參數的構造函數。使用它可以避免調用BeginInit和EndInit。你可以簡單地寫'Test.MainWindow.imageToChange.Source = new BitmapImage(new Uri(...));'。 – Clemens

+0

並且在同一個程序集中有一個資源包URI的簡寫形式:'pack:// application:,,,/Subfolder/ResourceFile'。簡而言之:'Test.MainWindow.imageToChange.Source = new BitmapImage(new Uri(「pack:// application:,,,/images/02.png」));'。 – Clemens