c# - 枚举上的数据触发以更改图像

标签 c# wpf

我有一个带有固定背景图像的按钮,我想在它上面显示一个小的叠加图像。选择哪个覆盖图像取决于相应 View 模型的依赖属性 (LapCounterPingStatus)。

这是我到目前为止得到的:

<Button>
    <Grid>
        <Image Stretch="None"> <!-- Background Image -->
            <Image.Style>
                <Style TargetType="{x:Type Image}">
                    <Setter Property="Source" Value="/Images/Pingn.png"/>
                </Style>
            </Image.Style>
        </Image>
        <Image Stretch="None" Panel.ZIndex="1"> <!-- Small Overlay Image -->
            <Image.Style>
                <Style TargetType="{x:Type Image}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="PingStatus.PING_UNKNOWN">
                            <Setter Property="Source" Value="/Images/RefreshOverlayn.png"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="PingStatus.PING_FAILURE">
                            <Setter Property="Source" Value="/Images/ErrorOverlayn.png"/>
                        </DataTrigger>
                        <DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="PingStatus.PING_SUCCESS">
                            <Setter Property="Source" Value="/Images/CheckmarkOverlayn.png"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Image.Style>
        </Image>
    </Grid>
</Button>

我的 View 模型的相关部分

public class ConfigurationViewModel
{
    public enum PingStatus { PING_UNKNOWN, PING_SUCCESS, PING_FAILURE };

    public PingStatus LapCounterPingStatus
    {
        get { return _lapCounterPingStatus; }
        set
        {
            _lapCounterPingStatus = value;
            RaisePropertyChanged(LapCounterPingStatusPropertyName);
        }
    }
}

现在,根本没有显示叠加图像。可能出了什么问题?


更新

我的 IDE 的跟踪窗口显示 System.ArgumentExceptionSystem.FormatException。 问题来源可能是 XAML 中未知类型的枚举 PingStatus 吗?

最佳答案

你需要两件事来让它工作:

1 - 在 XAML 文件的根元素中将 xmlns 引用添加到定义 Enum 的命名空间:

<UserControl ...
xmlns:my="clr-namespace:YourEnumNamespace;assembly=YourAssembly"> 

2 - 在 DataTriggerValue 属性中,使用 {x:Static} 形式:

 <DataTrigger Binding="{Binding Path=LapCounterPingStatus}" Value="{x:Static my:PingStatus.PING_UNKNOWN}">

请注意,Enum 类型必须以您在上面定义的 xmlns 前缀为前缀。

编辑:

如果您的枚举是在一个类中声明的,您需要使用以下语法:

{x:静态命名空间:ClassName+EnumName.EnumValue}

例如:

{x:Static my:ConfigurationViewModel+PingStatus.PING_UNKNOWN}

关于c# - 枚举上的数据触发以更改图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917033/

相关文章:

c# - 拦截按钮点击页面加载

c# - 后台 worker 不工作 WPF

c# - 在 C# 中,如何确定文件是二进制文件还是文本文件?

c# - MVVM Light 中有两种 ViewModel 吗?

wpf - 从 DataTemplate 中的控件获取 GridViewColumn

wpf - ItemsControl 在其上显示 Popup 后不会重新渲染

asp.net - 无法摆脱 "Login failed for user IIS APPPOOL\NETWORKSERVICE"

c# - 将字节作为参数传递给 c#?

c# - 新的 ASP.NET Core MVC 项目抛出异常

WPF ComboBox SelectedItem