views:

39

answers:

1
<Grid x:Name="ContentGrid">  
<Grid.Resources>          
<Image x:Key="art" Source="art.png" Stretch="None" />
</Grid.Resources>
<ContentControl Content="{Binding MyImg}" />
</Grid>     

public Image MyImg
{
    get { return (Image)GetValue(MyImgProperty); }
    set { SetValue(MyImgProperty, value); }
}

public static readonly DependencyProperty MyImgProperty =
    DependencyProperty.Register("MyImg", typeof(Image), typeof(MainPage), null);

public MainPage()
{

   InitializeComponent();

   ContentGrid.DataContext = this;

// Works. 

    MyImg = new Image() { Source = new BitmapImage(new Uri("art.png", UriKind.Relative)), Stretch = Stretch.None };

// Doesn't Work. Exception The parameter is incorrect. ???

    MyImg = ContentGrid.Resources["art"] as Image;
}

ContentGrid.Resources["art"] as Image don't reuturn null but an image with the same source as art.png but assigning to the dependency property fails! why?

+2  A: 

The second line isn't working because the image that you're referencing--the image in resources--doesn't have the source set up properly. In the first line, the one that works, you are properly setting up a BitmapImage and using a URI to reference the image. Your image in resources does not do that.

Therefore, try replacing your image in resources with this code:

<Image x:Key="art" Stretch="None">
    <Image.Source>
       <BitmapImage UriSource="art.png" />
    </Image.Source>
</Image>
Brian