这是我到目前为止所做的:
<Image Source="{Binding ImageSource"} />
<Button Content"Text" ImageSource="path/image.png" />
我知道有些事情不对。我想我无法看到ImageSource的定义。
我有几个按钮,只想为每个按钮创建一个独特的图像。我有一个我正在使用的按钮模板,它适用于文本。
<Label Content="TemplateBinding Content" />
感谢您的帮助!
答案 0 :(得分:7)
在你的情况下,它可以很容易!
将图像作为资源添加到项目中,然后添加到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模式,则可以执行以下操作
在您的XAML中:
<Button Focusable="False" Command="{Binding CmdClick}" Margin="0">
<Image Source="{Binding ButtonImage}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
</Image>
</Button>
在ViewModel中:
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;
答案 1 :(得分:0)
在您的XAML中:
<Button Focusable="False" Command="{Binding CmdClick}" Margin="0">
<Image Source="{Binding ImageSource,UpdateSourceTrigger=PropertyChanged} HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
</Image>
</Button>
在ViewModel中:
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));
OR:
string imagePath = "\\Images\\something.png";
this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Relative));