4

这是我到目前为止所拥有的:

<Image Source="{Binding ImageSource"} />

<Button Content"Text" ImageSource="path/image.png" />

我知道这里有些不对劲。我想我看不到 ImageSource 的定义位置。

我有几个这样的按钮,只想为每个按钮提供一个独特的图像。我有一个正在使用的按钮模板,它非常适合文本。

<Label Content="TemplateBinding Content" />

感谢你的帮助!

4

2 回答 2

8

在你的情况下,这很容易!

将图像作为资源添加到您的项目中,然后在 XAML 中使用如下内容:

<Button HorizontalAlignment="Left" Margin="20,0,0,20" VerticalAlignment="Bottom" Width="50" Height="25">
    <Image Source="image.png" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
    </Image>
</Button>

或者,更复杂的方式:

如果您使用 MVVM Pattern,您可以执行以下操作

在您的 XAML 中:

<Button Focusable="False" Command="{Binding CmdClick}" Margin="0">
    <Image Source="{Binding ButtonImage}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
    </Image>
</Button>

在您的视图模型中:

private Image buttonImage;

public Image ButtonImage 
{
    get
    {
       return buttonImage;
    }
}

在您的 ViewModel 的构造函数或它的初始化中的某处:

BitmapImage src = new BitmapImage();
src.BeginInit();
src.UriSource = new Uri("image.png", UriKind.Relative);
src.CacheOption = BitmapCacheOption.OnLoad;
src.EndInit();

buttonImage = new Image();
buttonImage.Source = src;
于 2012-07-31T17:44:28.703 回答
1

在您的 XAML 中:

 <Button Focusable="False" Command="{Binding CmdClick}" Margin="0">
     <Image Source="{Binding ImageSource,UpdateSourceTrigger=PropertyChanged} HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
     </Image>
 </Button>

在您的视图模型中:

 private BitmapImage _ImageSource;
 public BitmapImage ImageSource
 {
     get { return this._ImageSource; }
     set { this._ImageSource = value; this.OnPropertyChanged("ImageSource"); }
 }

 private void OnPropertyChanged(string v)
 {
     // throw new NotImplementedException();
     if (PropertyChanged != null)
         PropertyChanged(this, new PropertyChangedEventArgs(v));
 }
 public event PropertyChangedEventHandler PropertyChanged;

在您的 ViewModel 的构造函数或它的初始化中的某处:

 string str = System.Environment.CurrentDirectory;
 string imagePath = str + "\\Images\\something.png";
 this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Absolute));

或:</p>

 string imagePath = "\\Images\\something.png";
 this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Relative));
于 2017-08-15T11:57:47.063 回答