2017-07-17 77 views
4

我在我的WPF的Windows XAML定義的靜態資源:WPF:可以使用靜態資源只有一次

<Window.Resources> 
    <Image x:Key="MyImage" Source="../Icons/img.png" Width="16" Height="16" Stretch="None" /> 
</Window.Resources> 

我想用它時間:

<Grid> 
    <Button Content="{StaticResource MyImage}" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" /> 
</Grid> 

... 

<Grid> 
    <Button Content="{StaticResource MyImage}" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" /> 
</Grid> 

但它可以顯示作爲按鈕圖像只有一次。在最後一個按鈕上。第一個按鈕沒有圖像。

當我刪除第二個按鈕,然後它適用於第一個。如何多次使用StaticResource? Visual Studio GUI Designer在兩個按鈕上顯示圖像。

回答

10

默認情況下,XAML資源是共享的,這意味着只有一個實例可以重複使用,因爲它在XAML中被引用。

但是,Image控件(與任何其他UI元素一樣)只能有一個父控件,因此不能共享。

您可以將x:Shared屬性設置爲false:

<Image x:Key="MyImage" x:Shared="false" Source="../Icons/img.png" Width="16" Height="16"/> 

你通常不使用的用戶界面元素的資源。另一種方法是像這樣的BitmapImage資源:

<Window.Resources> 
    <BitmapImage x:Key="MyImage" UriSource="../Icons/img.png"/> 
</Window.Resources> 

<Button> 
    <Image Source="{StaticResource MyImage}" Width="16" Height="16"/> 
</Button>