IsEnabled为false时更改图像源

时间:2014-09-16 11:42:03

标签: wpf xaml

每当禁用/启用图像时,我都会尝试更改图像的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属性吗?

2 个答案:

答案 0 :(得分:2)

由于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 :(得分:2)

您的问题是,当您宣布Image.Source时,您已对Image值进行了“硬编码”。您还需要将其移至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有许多不同的方式来更新DependencyProperty,因此有一个Dependency Property Value Precedence list,它指定哪些来源应该能够覆盖从其他来源所做的更改。根据此列表,本地设置值将覆盖Style Trigger中的一个集合,但Style Trigger中的一个集合将覆盖Style Setter中的一个集合。

有关详细信息,请参阅链接页面。