Search code examples
xamluwpuser-controlsstylesuwp-xaml

How to access a style inside user control in UWP


I have a user control like this:

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

Nevertheless, I don't know, how can I set a style from mainwindow to user control? I have solved the problem to access to other properties like this:

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

And then

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

However, it doesn't work the style. There is no change in the sytle.

Thank you.


(Modification)

Below is a mainWindow part.

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

Behind-code part in 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); }
    }

Solution

  • You can use PropertyMetadata to initialise and set Style to your TextBlock. Like,

    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
    }