How to assign WPF resources to other resource tags

后端 未结 2 1637
情深已故
情深已故 2020-12-30 10:47

This is quite obscure, I may just be missing something extremely simple.

Scenario 1

Lets say I create a gradient brush, like this in my

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

    I was wondering when someone was going to ask about this.

    What you want to do in Scenario 1 is to effectively give a single resource an "alias." This is easily done by markup that seems obvious only after you see it. Suppose we have this in our App.xaml or somewhere:

    <ResourceDictionary>
      <LinearGradientBrush x:Key="GridRowSelectedBackBrushGradient" ... />
    </ResourceDictionary>
    

    To include an alias in another ResourceDictionary, just:

    <ResourceDictionary>
      <StaticResourceExtension x:Key="{x:Static SystemColors.HighlightBrushKey}"
                               ResourceKey="GridRowSelectedBackBrushGradient" />
    </ResourceDictionary>
    

    This looks up the brush object in the first ResourceDictionary and adds the same object to the second ResourceDictionary under a new key. This also works within a single ResourceDictionary.

    For your Scenario 2 the solution is just as simple:

    <Binding.ConverterParameter>
      <x:Array Type="{x:Type Brush}">
        <StaticResourceExtension ResourceKey="DataGridRowBackgroundBrush" />
        <StaticResourceExtension ResourceKey="DataGridRowBackgroundAltBrush" />
      </x:Array>
    </Binding.ConverterParameter>
    

    Again, the actual Brush objects found via the ResourceKey are added directly to the Brush[] array. No new Brush is created.

    I think we're all so used to using StaticResourceExtension with markup extension syntax (eg {StaticResource Xyz}) that it's easy to forget that it can also be used with regular element syntax as well.

    0 讨论(0)
  • 2020-12-30 11:33

    The markup you're working with doesn't go up far enough. You don't create a LinearGradientBrush, your first example: you just reference the resource. For example:

    <DataGrid HighlightBrushKey="{StaticResource GridRowSelectedBackBrushGradient}"  ....
    

    In your second example, I'd say that you want to declare the array as a resource:

    <x:Array Type="{x:Type Brush}" x:Key="MyArray">
      <SolidColorBrush Color="#EAF2FB" />
      <SolidColorBrush Color="#FFFFFF" />
    </x:Array>
    

    And then you can use

    <Binding RelativeSource="{RelativeSource Mode=Self}" 
             Converter="{StaticResource BackgroundBrushConverter}"
             ConverterParameter="{Staticresource MyArray}" />
    
    0 讨论(0)
提交回复
热议问题