开发者

How to add multiple copies of a resource item defined in XAML in C#?

I have two resources in my XAML which represent a Star and a Half Star:

<Path x:Key="HalfStar" Margin="2" Height="48" Stretch="Uniform" 
Data="M12.763,0 L12.763499,18.546873 L4.8750005,24.277998 L7.887928,15.004692 L0,9.273982 L9.7000046,9.273982 z" F
ill="Blue/>
<Path x:Key="FullStar" Margin="2" Height="48" Stretch="Uniform" 
Data="M12.763,0 L15.824005,9.2739811 L25.527,9.2739811 L17.638763,15.004915 L20.652,24.278 L12.763499,18.546873 L4.8750005,24.277998 L7.887928,15.004692 L0,9.273982 L9.7000046,9.273982 z" 
Fill="Blue"/>

I want to add a few of them to an ItemsControl in my C# code to represent a rating so I assign a property in my C# code of Type "Path" see below:

 Main.FullStar = ((Path)Resources["FullStar"]);
 Main.HalfStar = ((Path)Resources["HalfStar"]);

And then use these to add the Stars to the ItemsControl, however everytime I do this I get the following XAML error: "Element is already the child of another element.", however if I instance a simple object in my Code Behind e.g. a Circle I 开发者_如何学JAVAcan add this as many times as I want.

I think the issue is due to the Path having a Named Key which is being used in the C# defined version so the error makes sense in this case, however I want to add as many FullStars and HalfStars as needed, as it is only the Data i'm interested in. I would use the Geometry.Parse Method but it doesn't exist in Silverlight on Windows Phone.

All I need is to be able to use the Resources named "HalfStar" and "FullStar" and add them to a ItemsControl, the adding part must be done in Code Behind but the Stars and the Items Control are defined in XAML. My only solution is to use circles instead but this looks poor considering I have the resources I need and if I copy and paste them into the ItemsControl in XAML I can see them fine and they look great, currently I cannot add even one of the resources and cannot define them in C# due to limitations of the platform.


You can't re-use a single instance of a FrameworkElement in multiple places because it can only have one parent. You could, however, keep the PathGeometry for the two shapes as resources, create a new Path in code, and then set the PathGeometry to the Data property.

UPDATE: My previous suggestion doesn't work, apologies for the misdirection. The only other way around this that I can think of is to define the two different Path elements in separate UserControls, and then add new instances of each as appropriate in your code-behind. Not ideal I know, but I don't think there's another way around it. If you want to be able to style the Path elements, then you could just create a custom control and specify the style in Themes.xaml.

If you're trying to create a Rating control, you might want to take a look at this blog post, which describes how to use the one from the Silverlight Toolkit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜