加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

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

发布时间:2020-12-14 04:24:48 所属栏目: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="butto
我有一个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来显示它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读