0

I am trying to display a picture loaded by OpenFileDialog in a new window. The first way, which is doing that entirely in code works. I want to do it in another way, though. I attempt to add that image to resources and then use this for a given control.

XAML part:

<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# code:

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);
    }
}

Left column (done in the c# code) displays a loaded picture, but the right one does not (the one with binding usage). P.S. Regarding that every new picture is opened in a new window I realise that the ImageUri change notification is redundant in here. Please ignore this.

0

1 Answer 1

1

Drop the Image resource and bind directly to the ImageUri property of your Window:

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

Built-in type conversion will automatically convert from type Uri to ImageSource.

Sign up to request clarification or add additional context in comments.

2 Comments

I works, but I wondered how do do it by adding my Image to Window Reference
Having an Image element as resource doesn't make sense. You may however declare a BitmapImage as resource.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.