Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

Try:

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


<Button Style="{StaticResource buttonResource}" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top