Как создать стиль сетки с элементом, существующим внутри в WPF - PullRequest
0 голосов
/ 21 июня 2019

Я довольно новичок в 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 голосов
/ 21 июня 2019

Создайте UserControl с этим XAML и добавьте в него свойство зависимости.

Пример:

Создайте 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" />

...