2013-09-04 9 views
8

私はMain.xamlでこのResourceDictionaryを持っている:C#のイメージソースをXAML静的リソースにプログラムで設定する方法は?

<Window.Resources> 
    <ResourceDictionary> 
     <BitmapImage x:Key="Customer" UriSource="Icons/customer.png"/> 
     <BitmapImage x:Key="Project" UriSource="Icons/project.png"/> 
     <BitmapImage x:Key="Task" UriSource="Icons/task.png"/> 
    </ResourceDictionary> 
</Window.Resources> 

私が最初に使用して画像を設定します。

<Image Name="TypeIcon" HorizontalAlignment="Left" VerticalAlignment="Center" 
    Source="{StaticResource Customer}" Height="16" Width="16"/> 

私はカスタマーにプロジェクトからTypeIconSourceを変更しようとしていますC#メソッド。私が使用して試した

TypeIcon.Source = "{StaticResource Project}"; 

をしかし、私はこのエラーを取得する:

Cannot implicitly convert type string to System.Windows.Media.ImageSource

私はnew ImageSource()を使用して画像を定義しようとしたが、これはどちらか動作しません。

C#で画像のSourceをプログラムで変更するにはどうすればよいですか?多くのグーグルでの後

答えて

14

は、この質問を書きながら、私はそれを行う方法を考え出し:

TypeIcon.Source = (ImageSource) Resources["Project"]; 
2

あなたがたとえば、あなたが望む結果を得るためにImageSourceConverterクラスを使用することができます。

img1.Source = (ImageSource)new ImageSourceConverter().ConvertFromString("/Assets/check.png"); 
+1

'Media'名前空間には、'ユニバーサルアプリのため使用できませんSystem.Windows.Media.ImageSourceConverter' –

9

静的リソース用ではありませんが、とにかく便利です:)

つまり、動的にグリッドの背景を設定する方法

アプリのアイコンを設定する方法
var myBrush = new ImageBrush(); 
      var image = new Image 
          { 
           Source = new BitmapImage(
            new Uri(
             "pack://application:,,,/YourAppName;component/Images/Boo.png")) 
          }; 
myBrush.ImageSource = image.Source; 
MainGrid.Background = myBrush; 

すなわち動的

var idleIco = new Image 
      { 
       Source = new BitmapImage(
        new Uri(
         "pack://application:,,,/YourAppName;component/Images/idle.ico")) 
      }; 
SomeObjectYouAreUsingToSet.IconSource =idleIco.Source; 
関連する問題