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

时间:2018-08-06 05:13:35

标签: xaml uwp user-controls styles uwp-xaml

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

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

但是,它不适用于样式。样式没有变化。

谢谢。


(修改)

下面是mainWindow部分。

<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); }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用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
}