user2412672
user2412672

Reputation: 1479

WPF reuse XAML resource

I have a resource in my main window

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

I want to add it multiple times in C#, but it let's me to add only one occurrence of resources. If I try to add one more I get this error

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

I am adding like this.

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

So how I could add multiple occurrences of this resource?

Upvotes: 2

Views: 1114

Answers (2)

Faaiz Khan
Faaiz Khan

Reputation: 332

It is generally a good practice to use a resource dictionary for your resources or declare the resource in app.xaml file so its available throughout the application.

You can bind the resource as a static resource to any window or control. and in code you would have to write

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

Upvotes: 0

Nitin Purohit
Nitin Purohit

Reputation: 18578

use x:Shared = false. This will return the new instance of resource on every call.

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

Upvotes: 4

Related Questions