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

时间:2013-02-13 08:50:55

标签: wpf xaml .net-4.0 resourcedictionary staticresource

我有一个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 Content 1}}因此每个窗口应根据其ViewModel's 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> ,如下所示。

BoundText

但是,问题是两个Window都显示了BoundText属性的相同值,这意味着两个WPF Windows都有来自资源的 相同的 按钮控件实例,用于两个Windows。

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

修改 由于MSDN中提到的原因如下所示,我无法使用x:Shared =“False”属性来解决此问题:

  

•不得嵌套包含项目的ResourceDictionary   在另一个ResourceDictionary中。例如,你不能使用   x:在StyleDictionary中的一个Style内共享   已经是一个ResourceDictionary项目。

2 个答案:

答案 0 :(得分:8)

您是否尝试使用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来显示它。

答案 1 :(得分:3)

尝试:

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


<Button Style="{StaticResource buttonResource}" />