开发者

Why must I use "Resources" in WPF?

开发者 https://www.devze.com 2022-12-22 13:42 出处:网络
I\'m just diving into WPF and find this a little odd and frustrating to my style: Why can the value of something be a Resource but you can\'t set the value directly to what the Resource represents? Ex

I'm just diving into WPF and find this a little odd and frustrating to my style: Why can the value of something be a Resource but you can't set the value directly to what the Resource represents? Example:

This is valid:

<ToggleButton>
    <ToggleButton.Resources>
        <Image x:Key="cancelImage" Source="cancel.png" />
    </ToggleButton.Resources>
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Content" Value="{DynamicResource cancelImage}" />
        </Style>
    </ToggleButton.Style>
</ToggleButton>

But this is not:

<ToggleButton>
    <ToggleButton.Style>
        <Style TargetType="{x:Type ToggleButton}">
            <Setter Property="Content">
                <Setter.Value>
                    <Image Source="cancel.png" />
                </Setter.Value>
            </Setter>
        </Style>
    </ToggleButton.Style>
</ToggleButton>

What is the difference? Why don't both work? I don't like having to create a "Resource" for some things because it divides my code up and can make it more difficult to read.

And yes, I do know my example can be simplified like this

<ToggleButton>
    <Image Source="cancel.png" />
</ToggleButton>
开发者_Go百科

but that's not the point.


When working with setters, the value for the setter has to support the ability to be "frozen". That can be a value type (including structs and enums), or a class that derives from Freezable.

It may not help your aesthetic sense much, but it is often cleaner to declare all your resources at the top of the Resources section of the file (or ResourceDictionary), as opposed to adding them to the Resources of an individual style or control.

0

精彩评论

暂无评论...
验证码 换一张
取 消