[英]WPF: binding Bitmap source to XAML resources failure
我正在嘗試在新窗口中顯示由OpenFileDialog
加載的圖片。 第一種方法完全在代碼中起作用。 我想以另一種方式來做。 我嘗試將該圖像添加到資源中,然后將其用於給定控件。
XAML部分:
<Window.Resources>
<Image x:Key="imageResource">
<Image.Source>
<BitmapImage UriSource="{Binding ImageUri}" />
</Image.Source>
</Image>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Image Name="image" />
<Image Name="image2" Grid.Column="1" Source="{Binding imageResource}" />
</Grid>
C#代碼:
public partial class PicWindow : Window
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private Uri imageUri;
public Uri ImageUri
{
get
{
return imageUri;
}
set
{
imageUri = value;
NotifyPropertyChanged("ImageUri");
}
}
public PicWindow()
{
InitializeComponent();
}
public PicWindow(string filePath)
{
InitializeComponent();
imageUri = new Uri(filePath);
image.Source = new BitmapImage(imageUri);
}
}
左列(在c#代碼中完成)顯示已加載的圖片,而右列則不顯示(具有綁定用法的圖片)。 PS關於在新窗口中打開每張新圖片,我意識到ImageUri
更改通知在這里是多余的。 請忽略此。
刪除Image資源並直接綁定到Window的ImageUri
屬性:
<Image Name="image2" Grid.Column="1"
Source="{Binding ImageUri, RelativeSource={RelativeSource AncestorType=Window}}" />
內置類型轉換將自動從Uri
類型轉換為ImageSource
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.