从一个UserControl到父级UserControl中解析资源

4

我有一个名为UserControl1的用户控件,其中定义了一种风格资源。该用户控件包含一个UserControl2的实例,该实例引用该样式:

<UserControl x:Class="UserControl1">
    <UserControl.Resources>
        <Style x:Key="MyStyle" />
    </UserControl.Resources>

    <Grid>
        <UserControl2 />
    </Grid>
</UserControl>

<UserControl x:Class="UserControl2">
    <Grid Style="{StaticResource MyStyle}">
    </Grid>
</UserControl>

然而,即使它在UserControl1的资源中(逻辑树内),UserControl2也无法找到该样式资源。 我如何让UserControl2在UserControl1中找到资源?


样式为什么要放在UserControl内而不是ResourceDictionary中? - Blachshma
实际上它在一个ResourceDictionary中,但我将其包含在UserControl1的MergeDictionaries中。这是因为它包含一些类似主题的样式,我只想将其应用于UserControl1及其下属所有内容。 - thecoop
那么,在UserControl2中暴露一个新的依赖属性如何?这将允许您从外部设置模板。 - Blachshma
那样做是可行的,但有多层用户控件和许多样式。为所有这些暴露一个属性是不切实际的。 - thecoop
2个回答

1
你可以这么做,但我建议使用 ResourceDictionary 代替。
无论如何,如果你想以这种方式实现,你可以使用 FindAncestor 查找父级并访问 Parent 的 ResourceDictionary 中想要的 Resource
<UserControl x:Class="UserControl1">
    <UserControl.Resources>
        <Style x:Key="MyStyle" />
    </UserControl.Resources>

    <Grid>
        <UserControl2 />
    </Grid>
</UserControl>

<UserControl x:Class="UserControl2">
    <Grid Style="{Binding Resources[MyStyle], RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:UserControl1}}}">
    </Grid>
</UserControl>

因为 Resource 是一个字典,您可以像在代码后台一样使用 key 来访问它。

1

我曾经遇到过同样的问题,并且通过使用 DynamicResource 而不是 StaticResource 引用资源来解决了它:

<UserControl x:Class="UserControl2">
    <Grid Style="{DynamicResource MyStyle}">
    </Grid>
</UserControl>

编译器仍会发出警告,指出资源无法解析。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接