2017-05-24 76 views
0

我试图在新窗口中显示由OpenFileDialog加载的图片。 第一种方式,完全是在代码工作中完成的。不过,我想用另一种方式来做。我试图将该图像添加到资源,然后将其用于给定的控件。WPF:将位图源绑定到XAML资源失败

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#代码进行)显示一个加载的图片,但正确的不确实(具有结合使用)。 P.S.关于每个新图片都在新窗口中打开,我意识到ImageUri更改通知在这里是多余的。请忽略此。

回答

1

删除该图片资源,并直接绑定到窗口的ImageUri属性:

<Image Name="image2" Grid.Column="1" 
     Source="{Binding ImageUri, RelativeSource={RelativeSource AncestorType=Window}}" /> 

内置类型转换会自动从Uri类型转换为ImageSource

+0

我的工作,但我想知道如何通过将我的图像添加到'窗口引用' –

+1

有一个图像元素作为资源没有意义。您可能会声明一个BitmapImage作为资源。 – Clemens