【问题标题】:Convert Enum to string inside TextBlock text将 Enum 转换为 TextBlock 文本内的字符串
【发布时间】:2015-12-17 15:03:56
【问题描述】:

我有简单的Enum:

public enum StatusMessage
{
    Cancel,
    Done,
    [Description("In process...")]
    InProcess,
    [Description("We have delay...")]
    Delay,
    Waiting
}

还有GridViewColumn:

我的财产:

StatusMessage StatusMsg;

XAML:

<GridViewColumn Width="180" Header="Status" >
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding StatusMsg}" Foreground="{Binding StatusMsg,Converter={my:StatusMessageToColorConverter}}" />
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

我有这个EnumToStringConverter

public class EnumToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string EnumString;
        try
        {
            EnumString = Enum.GetName((value.GetType()), value);
            return EnumString;
        }
        catch
        {
            return string.Empty;
        }
    }

    // No need to implement converting back on a one-way binding 
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

现在我想在我的TextBlock 中使用这个Convertor

<TextBlock Text="{Binding StatusMsg, Converter={my:EnumToStringConverter}}" Foreground="{Binding StatusMsg,Converter={my:StatusMessageToColorConverter}}" />

所以问题是我有这个错误:

'my:EnumToStringConverter' 像标记扩展一样使用,但确实如此 不是从 MarkupExtension 派生的。

这是什么MarkupExtension

【问题讨论】:

    标签: wpf xaml enums


    【解决方案1】:

    您需要在 XAML 中声明 EnumToStringConverter 的实例。它可以是本地资源,也可以在 app.xaml 中声明以使其随处可访问。

    <Window.Resources>
        <my:EnumToStringConverter x:Key="DefaultEnumToStringConverter"/>
    </Window.Resources>
    

    然后像这样使用它:

    Text="{Binding StatusMsg, Converter={StaticResource DefaultEnumToStringConverter}}"
    

    注意转换器中的“StaticResource”一词。那就是标记扩展。这个告诉 WPF 去寻找带有键“DefaultEnumToStringConverter”的静态资源。 WPF 将搜索元素的可视化树以查找具有该键的资源。如果没有找到,它将在app.xaml 中的应用程序级别进行检查。

    MarkupExtensions 是包含在 {}、“x”、“binding”、“static”等中的属性开头的东西。它们使 WPF 能够将文本属性解析为有用的对象实例。您可以创建自己的 MarkupExtensions 来做一些非常酷的事情。

    在您的特定示例中,它正在抱怨,因为它正在从内部 Converter={my:EnumToStringConverter} 中寻找一个名为“my”的标记扩展。

    【讨论】:

    • 我有这个:xmlns:my="clr-namespace:myApplication.classes" 在我的项目(MyApplication)里面我有文件夹类,里面有这个 EnumToStringConverter 类
    • 这是xml namespace,而不是MarkupExtension。您仍然需要在您选择在其中声明 Converter 实例的任何 XAML 文件中使用 xmlns,因此请不要删除它。
    • 我把它放在 windows 资源中,我有这个错误:每个字典条目必须有一个关联的键。
    • 啊,对不起,那是我的错误。 “x:Name”应该是“x:Key”。我修正了我的例子。
    • 这应该是 StaticResource DefaultEnumToStringConverter
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    • 2019-01-08
    相关资源
    最近更新 更多