wpf

WPF Setter Value inlining


I have this code:

<Setter Property="WindowChrome.WindowChrome">
    <Setter.Value>
        <WindowChrome CaptionHeight="{x:Static SystemParameters.CaptionHeight}"/>
    </Setter.Value>
</Setter>

The application starts correctly, but it's verbose.

I tried to inline my code, so I wrote this:

<Setter Property="WindowChrome.WindowChrome"
        Value="{x:Static SystemParameters.CaptionHeight}"/>

But now if I run the application, it doesn't start. Why?


Solution

  • The property is of type WindowChrome, so it expects values of type WindowChrome.

    In the first case, it happens well. Also, you give to the WindowChrome instance a value of the correct type for its property CaptionHeight.

    In the second case, you're trying to assign to the WindowChrome property a value of a totally different type (the type of CaptionHeight).

    Now, if in your application there is only one single instance of WindowChrome, you can declare it as a StaticResource:

    <App.Resources>
      <WindowChrome x:Key="WindowChromeResource"
                    CaptionHeight="{x:Static SystemParameters.CaptionHeight}"/>
      </WindowChrome>
    </App.Resources>
    

    And then call it every time you need:

    <Setter Property="WindowChrome.WindowChrome"
            Value="{StaticResource WindowChromeResource}"/>
    

    If instead you need a dynamic number of different instances, it's definitely not possible to do this inline.

    Many developers had claimed about the WPF verbosity many times before you, but the WPF team has never improved that aspect. See this and this for wider discussion.