WPF - ボタンの背景画像を動的に変更するコード

WPF - ボタンの背景画像を動的に置き換えるコード
記事ディレクトリ
1 相対パス
2 絶対パス方式
2.1 画像がプロジェクトにインポートされていない場合
2.2 画像がプロジェクトにインポートされている場合
1 相対パスで
画像が検索されますプロジェクトのexeパスのリソースディレクトリ内

ImageBrush Brush1 = new ImageBrush();
string path = @"Resource/icon-submit.png";
BitmapImage img = new BitmapImage(new Uri(path, UriKind.Relative));
Brush1.ImageSource = img;
Testbutton.Background = Brush1 ;

2 絶対パス方式
2.1 プロジェクトに画像がインポートされていない場合
ImageBrush Brush1 = new ImageBrush();
string path = @"F:/Resource/icon-submit.png";
BitmapImage img = new BitmapImage(new Uri(path) , UriKind .Absolute));
Brush1.ImageSource = img;
Testbutton.Background = Brush1;

2.2 画像がプロジェクトにインポートされている場合は、
現在のプロジェクトとして @"pack://application: フラグを使用します。

ImageBrush ブラシ 1 = new ImageBrush();
文字列パス = @"pack://application:,,,/Resource/icon-提交.png";
BitmapImage img = new BitmapImage(new Uri(path, UriKind.Absolute));
ブラシ1.ImageSource = img;
テストボタン.背景 = ブラシ 1;
 

おすすめ

転載: blog.csdn.net/u014090257/article/details/130961919