Assign a ContentControl resource to an inherited ContentControl element
i have a trouble and i need your help. Here's my code:
public class CircleElement : ContentControl
{
public ContentControl me;
private FrameworkElement _parent;
public CircleElement()
{
if (_parent != null)
{
me = (ContentControl)_parent.FindResource("CircleRes");
me.Style = (Style)_parent.FindResource("CircleStyle");
}
}
The CircleElement inherits the ContentControl and I would like to assign the resource "CircleRes" and the style "CircleStyle" to it. Something like:
this = (ContentControl)_parent.FindResource("CircleRes");
this.Style = (Style)_parent.FindResource("CircleStyle");
This thing is not allowable.So to get around this problem I instantiated the ContentControl me element; but the开发者_如何学编程 code is a little messy!! How to get it more "elegant" ???
Thanks in advance
Paolo
Your requirement is a little strange but it is achievable in multiple ways...
Instead of having another content control (i.e. me
) why not set this
control's Content itself?
this.Content
= (ContentControl)_parent.FindResource("CircleRes");
((ContentControl)(this.Content)).Style
= (Style)_parent.FindResource("CircleStyle"); //*** Potential problem
Problem: The Potential problem statement is marked this way because your code (and mine too) sets the style "CircleStyle"
to "CircleRes"
resource by reference.
How? me
or ((ContentControl)(this.Content))
is nothing but "CircleRes"
resource!
This means if "CircleRes"
is referred in some other place, it will carry the "CircleStyle"
as its own style along with it. And if you set some new Style
to "CircleRes"
somewhere else then it will overwrite the Style
of "CircleRes"
wherever is used, including the above code (where intended style is "CircleStyle"
)
Solution: Use ContentTemplate
instead. Templates don't cause a visual's by instance reference.
So actually you should have a DataTemplate (say "CircleResTemplate") and set that as ContentTemplate to CircleElement
class.
this.ContentTemplate
= (DataTemplate)_parent.FindResource("CircleResTemplate");
this.Style
= (Style)_parent.FindResource("CircleStyle");
Let me know if this answers your question.
精彩评论