错误将ContentControl绑定到资源字典中的图像

时间:2010-09-16 13:42:08

标签: c# wpf silverlight windows-mobile

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

内容Grid.Resources [“art”] as Image不返回null,但是与art.png源相同但分配给依赖属性的图像失败!为什么呢?

1 个答案:

答案 0 :(得分:2)

第二行不起作用,因为您引用的图像 - 资源中的图像 - 没有正确设置源。在第一行中,您可以正确设置BitmapImage并使用URI来引用图像。资源中的图像不会这样做。

因此,请尝试使用以下代码替换资源中的图片:

<Image x:Key="art" Stretch="None">
    <Image.Source>
       <BitmapImage UriSource="art.png" />
    </Image.Source>
</Image>
相关问题