WPF控件作为资源字典中的StaticResource,用于多个WPF Windows?

我有一个Button控件作为资源字典中的资源,如下所示:
<!--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-->

我现在在2个不同的Windows .xaml文件中使用上面的按钮控件绑定到ContentControl控件的Content属性,其中每个Window都有自己的DataContext,因此每个窗口应根据其viewmodel的BoundText属性显示上面按钮控件的内容,如下所示每个窗口.

<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>

但是,问题是两个Window都显示了BoundText属性的相同值,这意味着两个WPF Windows都具有相同的资源按钮控制实例,在Windows中都使用.

如何解决此问题,以便每个窗口从资源获取单独的按钮控件,并仍然从自己的viewmodel显示BoundText属性的不同值?

编辑:
由于MSDN中提到的原因如下,我不能使用x:Shared =“False”属性解决此问题:

•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.

您是否尝试使用x:Shared属性
<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>

欲了解更多信息,请阅读here.

如果这不起作用,您可以在资源中存储模板,而不是按钮,并使用窗口内的ContentControl来显示它.

相关文章

Windows注册表操作基础代码 Windows下对注册表进行操作使用的...
黑客常用WinAPI函数整理之前的博客写了很多关于Windows编程的...
一个简单的Windows Socket可复用框架说起网络编程,无非是建...
Windows文件操作基础代码 Windows下对文件进行操作使用的一段...
Winpcap基础代码 使用Winpcap进行网络数据的截获和发送都需要...
使用vbs脚本进行批量编码转换 最近需要使用SourceInsight查看...