Applying a style to all derived classes in WPF

前端 未结 2 1121
既然无缘
既然无缘 2020-12-11 02:52

I want to apply a style to all classes derived from Control. Is this possible with WPF? The following example does not work. I want the Label, TextBox and Button to have a M

相关标签:
2条回答
  • 2020-12-11 03:43

    This is not possible in WPF. You have a couple of options to help you out:

    1. Create one style based on another by using the BasedOn attribute.
    2. Move the common information (margin, in this case) into a resource and reference that resource from each style you create.

    Example of 1

    <Style TargetType="Control">
        <Setter Property="Margin" Value="4"/>
    </Style>
    
    <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type Control}}">
    </Style>
    

    Example of 2

    <Thickness x:Key="MarginSize">4</Thickness>
    
    <Style TargetType="TextBox">
        <Setter Property="Margin" Value="{StaticResource MarginSize}"/>
    </Style>
    
    0 讨论(0)
  • 2020-12-11 03:44

    Here's one solution:

    <Window.Resources>
        <Style TargetType="Control" x:Key="BaseStyle">
            <Setter Property="Margin" Value="4"/>
        </Style>
        <Style BasedOn="{StaticResource BaseStyle}" TargetType="Button" />
        <Style BasedOn="{StaticResource BaseStyle}" TargetType="Label" />
        <Style BasedOn="{StaticResource BaseStyle}" TargetType="TextBox" />
    </Window.Resources>
    <Grid>
        <StackPanel Margin="4" HorizontalAlignment="Left">
            <Label>Zipcode</Label>
            <TextBox Name="Zipcode"></TextBox>
            <Button>get weather info</Button>
        </StackPanel>
    </Grid>
    
    0 讨论(0)
提交回复
热议问题