如何在 UWP 中访问用户控件内的样式

How to access a style inside user control in UWP

我有一个这样的用户控件:

<UserControl>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <HyperlinkButton Grid.Row="0" />

        <TextBlock Name="textblock" Grid.Row="1"
                   Text="{Binding dailyText, ElementName=userControl}">

        </TextBlock>
    </Grid>
</UserControl>

不过,我不知道,如何设置从主窗口到用户控件的样式?我已经解决了访问其他属性的问题:

public static readonly DependencyProperty MyContentProperty =
        DependencyProperty.Register("MyContent", typeof(object), typeof(Day), null);
public object MyContent
{
    get { return (object)GetValue(MyContentProperty ); }
    set { SetValue(MyContentProperty , value); }
}

然后

<local:Day MyContent="Hello World" /> 

但是,这种风格不起作用。样式没有变化。

谢谢。


(修改)

下面是主窗口部分。

<Page.Resources>
        <Style TargetType="TextBlock" x:Name="MyTextBlockStyle">
            <Setter Property="Foreground" Value="Blue" />
            <Setter Property="SelectionHighlightColor" Value="Red"/>
            <Setter Property="FontSize" Value="10"/>
        </Style>
</Page.Resources>

<local:Day MyStyle="{StaticResource MyTextBlockStyle}">

userControl 中的隐藏代码部分

public static readonly DependencyProperty MyStyleProperty =
        DependencyProperty.Register("MyStyle", typeof(Style), typeof(Day), null);
    public Style MyStyle
    {
        get { return (Style)GetValue(MyStyleProperty); }
        set { SetValue(MyStyleProperty, value); }
    }

您可以使用 PropertyMetadata 初始化并将 Style 设置为您的 TextBlock。喜欢,

public Style MyStyle
{
    get { return (Style)GetValue(MyStyleProperty); }
    set { SetValue(MyStyleProperty, value); }
}

public static readonly DependencyProperty MyStyleProperty =
    DependencyProperty.Register("MyStyle", typeof(Style), typeof(Day), 
                                new PropertyMetadata(null, OnStyleChange));

private static void OnStyleChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    var control = d as Day;
    control.textblock.Style = (Style)e.NewValue
}