如何使用WPF中存在的元素创建网格样式

时间:2019-06-21 11:27:58

标签: wpf styles resourcedictionary

我在WPF中很陌生。我的问题是我想用背景创建文本网格。下面是我的代码。 但是我想创建一种样式以在许多窗口中重用。 如何在ResourceDictionary中创建它?

enter image description here

<Grid>
    <ListBox Opacity="0.5" Width="100" Height="100"></ListBox>

    <TextBlock Text="My text" Foreground="Black" Opacity="0.5" FontSize="50" FontWeight="Bold">
        <TextBlock.LayoutTransform>
            <RotateTransform Angle="-45"></RotateTransform>
        </TextBlock.LayoutTransform>
    </TextBlock>
    <Grid.Background>
        <SolidColorBrush Color="LightPink" Opacity="0.5"/>
    </Grid.Background>        
</Grid>

我尝试编写一些代码:

<Style x:Key="myGridStyle" TargetType="{x:Type Grid}">
    <Setter Property="Background" Value="LightPink"/>
    <Setter Property="Opacity" Value="0.5"/>
    <!--what i have to code here?-->
</Style>

请帮助我继续。

谢谢你!

1 个答案:

答案 0 :(得分:0)

使用该XAML创建UserControl并将Dependency属性添加到其中。

示例:

创建一个UserControl并在.cs文件中添加以下代码

...
        public string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public static readonly DependencyProperty TextProperty =
            DependencyProperty.Register(nameof(Text), typeof(string), typeof(UserControl1), new PropertyMetadata(string.Empty));

        public UserControl1()
        {
            InitializeComponent();
        }
...

然后将此XAML代码添加到您的UserConstrol

    <Grid>
        <ListBox Opacity="0.5" Width="100" Height="100"></ListBox>

        <TextBlock Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}" Foreground="Black" Opacity="0.5" FontSize="50" FontWeight="Bold">
            <TextBlock.LayoutTransform>
                <RotateTransform Angle="-45"></RotateTransform>
            </TextBlock.LayoutTransform>
        </TextBlock>
        <Grid.Background>
            <SolidColorBrush Color="LightPink" Opacity="0.5"/>
        </Grid.Background>
    </Grid> 


最后测试


 <local:UserControl1 Text="something" />