如何绑定图像源? [英] How do I bind an Image Source?

查看:80
本文介绍了如何绑定图像源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Here is what I have so far:

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

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

我知道这里不对.我想我看不到ImageSource的定义位置.

I know something isn't right here. I guess I can't see where ImageSource is defined.

我有几个这样的按钮,只是想为每个按钮都有一个唯一的图像.我有一个正在使用的按钮模板,它非常适合文本.

I have several of these buttons and just want to have a unique image for each one. I have a button template that I am using and it works great for the text.

<Label Content="TemplateBinding Content" />

感谢您的所有帮助!

推荐答案

对于您来说,这很容易!

In your case, it can be very easy!

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

Add the images as resources to your project, then in XAML use something like the following:

<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模式,则可以执行以下操作

If you use the MVVM Pattern, you can do the following

在您的XAML中:

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

在您的ViewModel中:

In your ViewModel:

private Image buttonImage;

public Image ButtonImage 
{
    get
    {
       return buttonImage;
    }
}

在ViewModel的构造函数或其初始化中的某个位置:

And somewhere in the constructor of your ViewModel or the initialisation of it:

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;

这篇关于如何绑定图像源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆