【问题标题】:WPF Controls as StaticResource in Resource Dictionary, used in multiple WPF Windows?WPF 控件作为资源字典中的静态资源,用于多个 WPF 窗口?
【发布时间】:2013-02-13 08:50:54
【问题描述】:

我在资源字典中有一个 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's BoundText 属性值显示上述按钮控件的Content,如下所示。

<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 属性显示相同的值,这意味着两个 WPF 窗口都有 same 来自资源的按钮控件实例,用于两个窗口。

我怎样才能解决这个问题,以便每个窗口从资源中获得一个单独的按钮控件,并且仍然显示@的不同值987654328@ 来自他们自己的 ViewModel 的属性?

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

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

【问题讨论】:

    标签: wpf xaml .net-4.0 resourcedictionary staticresource


    【解决方案1】:

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

    【讨论】:

    • 谢谢。但是,我不能将该属性用作问题的 Edit: 部分中提到的原因。
    • 如果你使用上面的例子,你会使用下面的标签。
    • 太好了,x:Shared 刚刚解决了我的问题,目的是在不同的视图之间共享一个控件。
    【解决方案2】:

    试试:

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

    【讨论】:

    • 谢谢。我更新了我的问题以包括 Content Control 的使用,如何按照上述答案将每个 WPF 窗口(.xaml)中的 ContentControl 绑定到资源字典中的 Button 资源?
    • 我看不出会有什么不同。你能发布你的 ContentControl 的代码吗?
    • 我在两个 Window.xaml 文件中添加了 ContentControl 的使用代码。实际使用的不是按钮,而是不同的控件,因为我们想在以后的版本中更改资源 xaml 文件无需更改 Window.xaml 文件代码...
    • 在我写的例子中,buttonResource 不再是一个Button,而是一个样式,所以你不能将它用于ContentControl 的Content 属性。在这种情况下,您应该尝试来自 @Alex 的示例代码并将 x:Shared 属性设置为 false。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    相关资源
    最近更新 更多