0

I'm quite new in WPF. My problem is I want to create a Grid with text in background. Below is my code. But I want to create a style to reuse in many windows. How can I create it in 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>

I tried to code some line:

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

Please help me to continue.

Thank you in advanced!

Shai Nguyễn
  • 85
  • 1
  • 7
  • if you want all with that Style you can remove the x:Key else you have to add that key to the you want that style. https://stackoverflow.com/questions/2920830/how-to-apply-style-in-wpf-controls – kenny Jun 21 '19 at 11:36
  • discussion of global style https://stackoverflow.com/questions/3569974/wpf-global-style – kenny Jun 21 '19 at 11:38

1 Answers1

0

Create a UserControl with that XAML and add Dependency Property to it.

Example :

Create a UserControl and add following code in your .cs file

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

then add this XAML code to your 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> 


and finally test it


 <local:UserControl1 Text="something" />

Zer0
  • 1,146
  • 6
  • 15