wpf - 将 Enum 转换为 TextBlock 文本中的字符串

标签 wpf xaml enums

我有简单的枚举:

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

GridViewColumn:

我的属性(property):

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' is used like a markup extension but does not derive from MarkupExtension.

这是什么MarkupExtension

最佳答案

您需要在 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”的标记扩展。

关于wpf - 将 Enum 转换为 TextBlock 文本中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337755/

相关文章:

c# - 绑定(bind)到数组支持的属性

xaml - Windows 8 Metro::什么是 AutomationProperties.AutomationId 和 AutomationProperties.Name

c# - Xamarin.Forms。 XAML Label IsVisible 条件未按预期进行评估

c++ - 枚举类 vector 的初始值设定项列表问题

java - Java中如何存储和重用一组相关的常量值?

wpf - 扩展器、网格和列表框 = 无虚拟化

wpf - 在 MVVM 中创建 ViewModel 的最佳位置

wpf - Windows Phone 用户控件不会在 ListBox 中拉伸(stretch)

c# - DependencyProperty 不适用于 CustomControl

WPF 工具包 Propertybox 不显示可为 null 的枚举