WPF控件作为资源字典中的StaticResource,在多个WPF窗口中使用?

WPF控件作为资源字典中的StaticResource,在多个WPF窗口中使用?,wpf,xaml,.net-4.0,resourcedictionary,staticresource,Wpf,Xaml,.net 4.0,Resourcedictionary,Staticresource,我有一个按钮控件作为资源字典中的资源,如下所示: <!--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="buttonR

我有一个按钮控件作为资源字典中的资源,如下所示:

<!--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-->
但是,问题是两个窗口的BoundText属性显示相同的值,这意味着两个WPF窗口都具有相同的资源按钮控件实例(在两个窗口中使用)

如何解决此问题,使每个窗口从资源中获得一个单独的按钮控件,并且仍然从其自己的视图模型中为
BoundText
属性显示不同的

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

•包含项目的ResourceDictionary不得嵌套 在另一个资源字典中。例如,您不能使用 x:为样式中的ResourceDictionary中的项共享 已是ResourceDictionary项

试试看:


您是否尝试使用
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>

欲了解更多信息,请阅读


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

谢谢。我更新了我的问题,以包括内容控制的使用,如何根据上述答案将每个WPF窗口(.xaml)中的内容控制绑定到资源字典中的按钮资源?我看不出会有什么不同。您可以发布ContentControl的代码吗?我在两个Window.xaml文件中都添加了ContentControl的使用代码。。实际使用的不是一个按钮,而是一个不同的控件及其名称,因为我们希望在未来的版本中更改资源xaml文件,而不必更改Window.xaml文件代码……在我编写的示例中,buttonResource不再是一个按钮,而是一种样式,因此不能将其用于ContentControl的Content属性。在这种情况下,您应该尝试@Alex中的示例代码,并将x:Shared属性设置为false。谢谢。但是,我不能使用该属性作为问题的编辑:部分中提到的原因。很好,x:Shared刚刚解决了我的问题,目的是在不同的视图之间共享一个控件。
<Style TargetType="Button" x:Key="buttonResource">
    <Setter Property="Content" Value="{Binding BoundText}" />
</Style>

<Button Style="{StaticResource buttonResource}" />
<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>