tags:

views:

155

answers:

2

Hi,

I am working on a PRISM / CAL solution, but the problem may be WPF specific:

If I create one instance of an control (e.g. TextBlock) and add it as child to a StackPanel, there is no way to add it as "child" to another StackPanel (parent already set error). I kind of understand the reason (it also occurs when using the RegionManager).

But what is the suggested way if a visual control is very complex and should be created only one time and used in two places? I agree that is does not really make sense to show an identical control 2 times on the screen, but there might be cases where it is useful (e.g. an "Close All" Button).

I know that in the button case, I should just create two buttons both databound to one ICommand. But does this rule also apply with much more complex controls (always create new instances)...

I stumbled on this problem when creating a layout switcher, which creates the button list and the stack panel for each GUI seperately, but uses a static ObservableCollection of buttons as source (which causes strange bugs)..

Any ideas on this topic?

Chris

+1  A: 

This is normally handled by templates. That is, you abstract out the data into a particular type, and associate a template with that type. Then you place the instance of that data any number of times into your visual tree and have WPF render it with the template.

In short, don't add a TextBlock to your StackPanel. Instead, add an instance of your data type (eg. Customer) and associate a DataTemplate with the Customer type. There is no way to parent the same UIElement in multiple places.

HTH, Kent

Kent Boogaart
Thanks, I thought so... I am currently working with Code Only (still faster, not used to XAML and in multi-target-envs with Silverlight its messy anyway).. Changed the collection to ICommands and used "new" buttons for all controls. Then everything is fine..
Christian
A: 

You can add your control (or collection of controls) as a resource and refer to them via binding in your controls. This will implicitly create a copy (they will be Freezable and WPF will copy them).

Generally you should be using DataTemplates as Kent suggests, but if you have a special case, this will likely work.

Anderson Imes