【问题标题】:How to access a style inside user control in UWP如何在 UWP 中访问用户控件内的样式
【发布时间】:2019-01-13 00:24:29
【问题描述】:

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

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

【问题讨论】:

  • SO 不是免费的代码交付网站。您尝试过什么需要用代码解释?请参考这个stackoverflow.com/help/how-to-ask
  • 感谢您纠正我的错误。此修改符合您的意图吗?
  • 显示“主窗口中的样式”部分

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


【解决方案1】:

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

【讨论】:

  • 我遇到了这个问题。谢谢它的工作:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-27
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多