WPF controls like StaticResource in resource dictionary used in multiple Windows WPF?

I have a Button control as a resource in the resource dictionary, as shown below:

<!--ButtonResources.xaml file--> <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Button x:Key="buttonResource" Content={Binding BoundText}/> </ResourceDictionary> <!--ButtonResources.xaml file--> 

Now I use this control bound to the Content property of the ContentControl controls in 2 different Windows .xaml files , where each Window has its own DataContext and so each window should display the Content above button controls based on its ViewModel's BoundText property BoundText , as shown below for each window.

 <Window x:Class="TestClass1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="ButtonResources.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> <Grid> <ContentControl Content={StaticResource buttonResource}/> </Grid> </Window> 

But the problem is that both windows display the same value for the BoundText property, which means that both WPF windows have the same instance of the control button from the resource used in both Windows.

How can I solve this problem, so that each window receives a separate button control from the resource and still displays values different for the BoundText property from its own ViewModel

Edit: For the reason mentioned in MSDN , as shown below, I cannot use the x: Shared = "False" attribute to solve this problem:

• A ResourceDictionary containing elements must not be nested within another ResourceDictionary. For example, you cannot use x: common to elements in a ResourceDictionary that is in a style that is already a ResourceDictionary element.

+7
source share
2 answers

Have you tried to use the x:Shared attribute?

 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Button x:Shared="False" x:Key="buttonResource" Content={Binding BoundText}/> </ResourceDictionary> 

Read more here .

If this does not work, you can save the template in your resource instead of the button and use the ContentControl inside your window to display it.

+8
source

Try:

 <Style TargetType="Button" x:Key="buttonResource"> <Setter Property="Content" Value="{Binding BoundText}" /> </Style> 
 <Button Style="{StaticResource buttonResource}" /> 
+3
source

All Articles