【问题标题】:How do I bind an Image Source?如何绑定图像源?
【发布时间】:2022-03-15 15:53:26
【问题描述】:
这是我目前所拥有的:
<Image Source="{Binding ImageSource"} />
<Button Content"Text" ImageSource="path/image.png" />
我知道这里有些不对劲。我想我看不到 ImageSource 的定义位置。
我有几个这样的按钮,只是希望每个按钮都有一个独特的图像。我有一个正在使用的按钮模板,它非常适合文本。
<Label Content="TemplateBinding Content" />
感谢您的帮助!
【问题讨论】:
标签:
c#
image
binding
expression-blend
【解决方案1】:
在你的情况下,这很容易!
将图像作为资源添加到您的项目中,然后在 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>
在您的视图模型中:
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;
【解决方案2】:
在您的 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));
或:
string imagePath = "\\Images\\something.png";
this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Relative));