c# - WPF 图像控件 : Trigger stops working once Source is modified in code

标签 c# wpf

我在更改 WPF 图像控件的“源”属性时遇到了一些问题。

我定义了三个图像源:

<Window.Resources>
    <BitmapImage x:Key="eyeSelImage" UriSource="/Images/eye-Sel.png" />
    <BitmapImage x:Key="eyeSelHlImage" UriSource="/Images/eye-SelHl.png" />
    <BitmapImage x:Key="eyeDisabled" UriSource="/Images/eye-Disabled.png" />
</Window.Resources>

我的图像定义如下所示:

<Image x:Name="testImage" Width="100" Height="100">
    <Image.Style>
        <Style TargetType="{x:Type Image}">
            <Setter Property="Source" Value="{StaticResource eyeSelImage}"/>
            <Style.Triggers>
                <Trigger Property="IsEnabled" Value="False">
                    <Setter Property="Source" Value="{StaticResource eyeDisabled}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Image.Style>
</Image>

它按预期工作。如果禁用图像控件,则图像会更改。一旦启用,它就会变回。我通过制作一个按钮 (btn_DisableEnable) 对此进行了测试,单击该按钮会切换“testImage”的“IsEnabled”属性。

但是,一旦我在代码中更改了“testImage”图像控件的“来源”,“IsEnabled”触发器似乎就停止工作了。我制作了另一个按钮,并在其“点击”事件处理程序中执行以下操作:

BitmapImage tempImage = new BitmapImage();
tempImage.BeginInit();
tempImage.UriSource = new Uri("pack://application:,,,/testApp1;component/Images/eye-SelHl.png");
tempImage.EndInit();
testImage.Source = tempImage;

按下此按钮后,图像源正确更改为“eyeSelHlImage”资源。但是,当单击“btn_DisableEnable”时,图像不再更改为禁用表示并返回。

可能是什么问题?非常感谢所有帮助。

谢谢!

最佳答案

由于可以通过不同的机制(触发器、样式、主题、继承等)设置依赖属性,因此定义了一个“设置”优先级列表。

你可以找到它here .

如您所见,本地值 - 即,如果您使用代码或 XAML 或使用 SetValue 直接设置属性方法 - 比样式触发器具有更高的优先级。

因此,通过代码设置 Source 属性优先于您的触发器可能设置的值。

这就是为什么在调用代码后触发器不再起作用的原因。

关于c# - WPF 图像控件 : Trigger stops working once Source is modified in code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34436487/

相关文章:

c# - RadioButtonFor 中的默认选择

c# - 主服务器宕机

c# - Kentico 中的多对多关系

c# - 编写 Visual Studio 2010 插件,想在代码编辑器中显示一个像 Resharper 这样的工具箱

c# - WPF - 更改对象属性时通知 ViewModel

c# - 隐藏工具栏绑定(bind)错误

wpf - 自动收报机上带有标签的垂直 slider

c# - MVC Controller 的 AJAX 参数不是 NULL?

c# - IOC : Wiring up dependencies on event handlers

wpf - 在 Wpf 中显示与 MVVM 中的 ListView 不同的 View (缩略图、详细信息列表)