簡體   English   中英

如何綁定圖像源?

[英]How do I bind an Image Source?

這是我到目前為止:

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

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

我知道有些事情不對。 我想我無法看到ImageSource的定義。

我有幾個按鈕,只想為每個按鈕都有一個獨特的圖像。 我有一個我正在使用的按鈕模板,它適用於文本。

<Label Content="TemplateBinding Content" />

感謝你的幫助!

在你的情況下,它可以很容易!

將圖像作為資源添加到項目中,然后在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;

在你的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));

要么:

 string imagePath = "\\Images\\something.png";
 this.ImageSource = new BitmapImage(new Uri(imagePath, UriKind.Relative));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM