WPF 用户控件样式 -- 如果控件在外部程序集中,如何从父级设置样式?

7
基本上,我有以下结构:
<Window ...
        xmlns:my="http://schemas.company.com/WPF/Controls"
        >
    <Window.Resources>
        <Style x:Key="MyStyle1" TargetType={x:Type TextBlock}>
            ...
        </Style>
    </Window.Resources>
    <Grid x:Name="LayoutRoot">
        <my:MyUserControl1 />
        <my:MyUserControl1 />
        <my:MyUserControl2 />
        <my:MyUserControl2 />
    </Grid>
</Window>

<UserControl ...
             >
    <TextBlock Style={ ?? What Goes Here ??} />
</UserControl>

如何应用在 Window 资源中声明的样式,以便将其应用到从外部程序集中引用的 UserControl 中?
2个回答

5
如果你希望样式应用于所有的TextBlock,包括MyUserControl中的TextBlock,只需省略x:Key,它就会隐式地应用。
<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Green"/>
</Style>

如果您希望明确设置它,可以在UserControl中使用DynamicResource
<Window.Resources>
    <Style x:Key="MyStyle1" TargetType="{x:Type TextBlock}">
        <Setter Property="Foreground" Value="Green"/>
    </Style>
</Window.Resources>
<StackPanel>
    <my:UserControl1 />
    <my:UserControl1 />
    <my:UserControl1 />
    <my:UserControl1 />
</StackPanel>

<UserControl ...>
    <TextBlock Style="{DynamicResource MyStyle1}" Text="TextBlock"/>
</UserControl>

1
@Aaron:如果你使用StaticResource,你会得到一个异常,上面写着“找不到名为'MyStyle1'的资源。资源名称区分大小写”。 - Fredrik Hedblad
好的,我注意到资源在一个窗口中,而不是App.xaml或其他合并的ResourceDictionary中。楼主应该将其从窗口中移出... - Aaron McIver
@Aaron:一开始我也是这么想的,但可能存在某些情况下这很有用。例如,两个不同的窗口可以以不同的方式为同一个用户控件设置样式。虽然我无法想出需要这样做的场景,但仍然…… - Fredrik Hedblad
真的;但正如你所说...使用案例很难找到。 - Aaron McIver

0

试试这个:

<TextBlock Style={ StaticResource MyStyle1} />

希望这可以帮助你 WPF中的样式介绍


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