2010-09-16 37 views
0
<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 [「藝術」]作爲圖片不reuturn空但具有相同的源作爲art.png但分配給依賴屬性的圖像失敗!爲什麼?錯誤從資源字典綁定ContentControl中到圖像

回答

2

第二行不起作用,因爲您引用的圖像 - 資源中的圖像 - 沒有正確設置源。在第一行中,您可以正確設置BitmapImage並使用URI來引用圖像。你在資源中的形象不會那樣做。

因此,嘗試使用此代碼替換資源圖像:

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