开发者

WPF UserControl Style -- How do I set the style from the parent if the control is in an external assembly?

开发者 https://www.devze.com 2023-02-15 21:29 出处:网络
Basically I have the following structure: <Window ... xmlns:my=\"http://schemas.company.com/WPF/Controls\"

Basically I have the following structure:

<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>


How do I apply the style declared in the Window resources so that it goes to the UserControl that is being pulled from an external assembly?


If you want the Style to be applied to all TextBlocks, including the ones in MyUserControl, just leave the x:Key out and it will be applied implictly

<Style TargetType="{x:Type TextBlock}">
    <Setter Property="Foreground" Value="Green"/>
</Style>

If you want it to be set explicitly you can use DynamicResource in the UserControls

<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>


Try this :

<TextBlock Style={ StaticResource MyStyle1} />

I hope this help you Introduction to Styles in WPF

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号