Apply WPF styles like CSS and Html

I doubt it is possible, but just wanted to confirm.

I am writing a simple WPF application and want my style to be defined externally, so you could basically load the style as an external resource. A bit like CSS and HTML usually stand out ...

However, one thing that bothers me is that with HTML and CSS it is more like an external approach, CSS is element oriented and applied to the corresponding elements. However, with WPF it seems that the opposite is true, you should tell the element which styles it should apply, however this does not seem very dynamic. So I just want to know if there is a way to apply styles, so the styles just target the elements.

An example would be something like:

<Style TargetType="{x:Type TextBox}" TargetElement="{x:Name SomeTextboxElement}">
    <Setter Property="Width" Value="Auto"/>
</Style>

As usual, you need to specify the key with the style, then get the (SomeTextboxElement) element to match the style key.

It seems a little silly to have an explicit indication of each element of the style binding, it should be more hierarchical and filter (which may be possible, I just don't know how to do this), and not be a one-to-one mapping. Forever draw an entire application ...

Hope this makes sense ...

+5
source share
3 answers

, , , , wpf, ( : ). , , , :

<Style TargetType="{x:Type TextBox}">
   <Setter Property="Width" Value="Auto"/>
</Style>

, TargetElement.

, , , , . "Tag" , . , 3 :

        <Style.Triggers>
            <Trigger Property="Tag" Value="delete">
                <Setter Property="Background" Value="Red"></Setter>
            </Trigger>
            <Trigger Property="Tag" Value="confirm">
                <Setter Property="Background" Value="Green"></Setter>
            </Trigger>
        </Style.Triggers>

- . , , , :

  • WPF DependencyProperty "ParentVisual", .
  • WPF DepencyProperty, "VisualType"

, / ParentVisual.VisualType.

CSS WPF, TextBox, , "subnavi", .

Grid Border#subnavi TextBox
{
    backgroundColor:#FF0000;
}

WPF, Multitrigger TextBox :

  <MultiTrigger>
   <Condition Property="ParentVisual.VisualType" Value="Border"></Condition>
   <Condition Property="ParentVisual.Name" Value="subnavi"></Condition>
   <Condition Property="ParentVisual.ParentVisual.VisualType" Value="Grid"></Condition>
   <Setter Property="Background" Value="Red"/>
  </MultiTrigger>

, , DependencyProperties , , wpf.

, WPF: WPF WPF-, , , . , CSS .

EDIT: , DependencyObject, Visual , .

+2

. , css, . , : " , 80"

<Style TargetType="{x:Type Button}">
    <Setter Property="Width" Value="80"/>
</Style>

: , , , . " " , .

.

0

All Articles