【问题标题】:Change Image Source when IsEnabled is false当 IsEnabled 为 false 时更改图像源
【发布时间】:2014-11-10 03:34:23
【问题描述】:

每当图像被禁用/启用时,我都会尝试更改图像的 Source 属性。 我检查了this 并且工作正常,只要图像被禁用,不透明度就会改变。但是,一旦我尝试设置 Source 属性,它就不起作用。它被忽略。 这是我的标记:

<Image Source="/My_Project;component/Images/countdown.png" Width="75">
    <Image.Style>
        <Style TargetType="Image">
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Source" Value="/My_Project;component/Images/countdown.disabled.png"/> <!-- does not work -->
                    <!-- <Setter Property="Opacity" Value="0"/> this works! -->
                </Trigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

我错过了什么吗?甚至可以更改 Source 属性吗?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    由于Dependency Property Value Precedence,这仅在您没有为Source 属性设置local value 时才有效,而是通过样式设置它:

    <Image Width="75">
        <Image.Style>
            <Style TargetType="Image">
                <Setter Property="Source"
                        Value="/My_Project;component/Images/countdown.png"/>    
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Source"
                            Value="/My_Project;component/Images/countdown.disabled.png"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
    

    【讨论】:

    • 哈哈!我们在这里写相同的答案吗? +1 还提到了依赖属性值优先级。
    • 太好了,谢谢! @Sheridan 抱歉,我也无法将您的答案标记为已接受,我只是长期选择第一个 :) 感谢你们俩!
    • @DavideDeSantis,我非常高兴您将接受的答案授予您喜欢的任何人,但仅供将来参考,我们应该将其授予最佳 答案,而不是第一个答案。
    • @Sheridan 我知道,当然你是对的。我只是在想你基本上写了同样的东西,但我又读了一遍,你的答案比克莱门斯的要详细一点,所以你去,更正:)
    • 我并不是想让您更改关于 this 问题的已接受答案...这就是为什么我将仅供将来参考放在我的评论。
    【解决方案2】:

    您的问题是您在声明Image 时已经“硬编码”了Image.Source 值。您也需要将其移至Style。试试这个:

    <Image Width="75">
        <Image.Style>
            <Style TargetType="Image">
                <Setter Property="Source" 
                    Value="/My_Project;component/Images/countdown.png"/>
                <Style.Triggers>
                    <Trigger Property="IsEnabled" Value="False">
                        <Setter Property="Source" 
                            Value="/My_Project;component/Images/countdown.disabled.png"/>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Image.Style>
    </Image>
    

    这样做的原因是因为 WPF 有许多不同的方法来更新 DependencyPropertyDependency Property Value Precedence list,它指定哪些源应该能够覆盖从其他源所做的更改。根据此列表,本地设置值将覆盖Style Trigger 中的一组值,但Style Trigger 中的一组值将覆盖Style Setter 中的一组值。

    有关更多信息,请参阅链接页面。

    【讨论】:

    • 我喜欢您避免水平滚动条的代码格式 :-)
    • 我们可以在这个网站上使用自动文本换行......它已经过期了。 :)
    猜你喜欢
    • 1970-01-01
    • 2011-12-09
    • 2015-10-04
    • 1970-01-01
    • 2019-12-21
    • 1970-01-01
    • 2013-03-31
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多