2012-07-31 87 views
2

这是我到目前为止有:如何绑定图像源?

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

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

我知道的东西是不是就在这里。我想我看不到ImageSource的定义。

我有几个这些按钮,只是想为每一个都有一个独特的图像。我有一个我正在使用的按钮模板,它对文本非常有用。

<Label Content="TemplateBinding Content" /> 

感谢您的帮助!

回答

6

就你而言,它可以非常简单!

的图像作为资源添加到您的项目,然后在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> 

在您的视图模型:

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; 
0

在您的XAML:

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

在您的视图模型:

private Image buttonImage; 

public Image ButtonImage 
{ 
    get 
    { 
     return buttonImage; 
    } 
} 
在你的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));