WPF Controls as StaticResource in Resource Dictionary, used in multiple WPF Windows?

VSS picture VSS · Feb 13, 2013 · Viewed 17k times · Source

I have a Button control as a resource in Resource Dictionary as 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-->

I now use this above button control bound to Content property of ContentControl controls in 2 different Windows .xaml files where each Window has its own DataContext and thus each window should display the Content of above button control based on its ViewModel's BoundText property value as 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 Window's display same value for the BoundText property which means that both the WPF Windows have same instance of button control from resource, used in both the Windows.

How can I resolve this problem such that each Window gets a separate button control from the resource and still display different values for the BoundText property from their own ViewModel?

Edit: For the reason mentioned in MSDN as below, I can't use x:Shared="False" attribute to resolve this:

•The ResourceDictionary that contains the items must not be nested within another ResourceDictionary. For example, you cannot use x:Shared for items in a ResourceDictionary that is within a Style that is already a ResourceDictionary item.

Answer

Alex Shtof picture Alex Shtof · Feb 13, 2013

Did you try 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>

For more info read here.

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