如何绑定图像源?

5

这是我目前的进展:

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

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

我知道这里有些不对劲。我猜我看不到ImageSource的定义。
我有几个这样的按钮,只想为每个按钮设置一个唯一的图像。我有一个正在使用的按钮模板,对文字效果很好。
<Label Content="TemplateBinding Content" />

感谢您的帮助!
2个回答

10
在您的情况下,这非常容易!
将图像作为资源添加到您的项目中,然后在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
在你的 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));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接