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

前端之家收集整理的这篇文章主要介绍了WPF控件作为资源字典中的StaticResource,用于多个WPF Windows?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个Button控件作为资源字典中的资源,如下所示:
  1. <!--ButtonResources.xaml file-->
  2. <ResourceDictionary
  3. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  5. <Button x:Key="buttonResource" Content={Binding BoundText}/>
  6. </ResourceDictionary>
  7. <!--ButtonResources.xaml file-->

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

  1. <Window x:Class="TestClass1"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  4. <Window.Resources>
  5. <ResourceDictionary>
  6. <ResourceDictionary.MergedDictionaries>
  7. <ResourceDictionary Source="ButtonResources.xaml"/>
  8. </ResourceDictionary.MergedDictionaries>
  9. </ResourceDictionary>
  10. </Window.Resources>
  11. <Grid>
  12. <ContentControl Content={StaticResource buttonResource}/>
  13. </Grid>
  14. </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属性
  1. <ResourceDictionary
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  4. <Button x:Shared="False" x:Key="buttonResource" Content={Binding BoundText}/>
  5. </ResourceDictionary>

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

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

猜你在找的Windows相关文章