WPF重用XAML资源

时间:2014-02-01 07:01:51

标签: c# .net wpf xaml

我的主窗口中有一个资源

<Window.Resources>
        <Path x:Key="QueenPiece" Width="31.6667" Height="44.7292" Canvas.Left="22.1667" Canvas.Top="15.4375" Stretch="Fill" Fill="#FF000000" Data="F1 M 38,15.4375C 39.3788,15.4375 41.3434,16.4942 41.7781,17.4167L 49.0833,17.4167L 42.75,25.3333L 42.8575,30.7597L 49.0833,33.25L 42.5936,33.25C 42.9492,38.7231 43.2787,42.8806 44.1936,46.083L 48.2917,47.5L 45.4222,47.5C 48.7019,57.3679 53.8333,56.9346 53.8333,60.1667L 22.1667,60.1667C 22.1667,56.9346 27.2981,57.3679 30.5778,47.5L 27.7083,47.5L 31.8064,46.083C 32.7212,42.8806 33.0508,38.723 33.4064,33.25L 26.9167,33.25L 33.1425,30.7597L 33.25,25.3333L 26.9167,17.4167L 34.2218,17.4167C 34.6566,16.4942 36.6212,15.4375 38,15.4375 Z "/>
</Window.Resources>

我想在C#中多次添加它,但它让我只添加一次资源。如果我尝试再添加一个,我会收到此错误

Specified Visual is already a child of another Visual or the root of a CompositionTarget. 

我这样添加。

private void cell_MouseDown(object sender, MouseButtonEventArgs e)
{
     Path queen = this.Resources["QueenPiece"] as Path;
     ChessBoard.Children.Add(queen);
}

那么如何添加多次出现的资源?

2 个答案:

答案 0 :(得分:4)

使用x:Shared = false。这将在每次调用时返回新的资源实例。

<Path x:Key="QueenPiece" Width="31.6667" x:Shared="false"

答案 1 :(得分:0)

通常,优先使用resource dictionary作为资源,或在app.xaml文件中声明资源,以便在整个应用程序中使用。

您可以将资源作为静态资源绑定到任何窗口或控件。在代码中你必须写

Path queen= App.Current.Resources["QueenPiece"] as path;
ChessBoard.Children.Add(queen);