将枚举类型绑定到文本框

发布于 2024-09-19 00:32:18 字数 285 浏览 7 评论 0原文

我将 textbox.text 值绑定到枚举类型。 我的枚举看起来像

public enum Type
    {

        Active,

        Selected,

        ActiveAndSelected
    }

我不想完成的是在文本框“活动模式”而不是“活动”等上显示。可以这样做吗?如果我能在 XAML 中完成这一点,那就太好了 - 因为我在样式文件 style.xaml 中拥有的所有绑定

我试图使用描述属性,但似乎这还不够

I bind textbox.text value to enum type.
My enum looks like that

public enum Type
    {

        Active,

        Selected,

        ActiveAndSelected
    }

What I wan't to acomplish is to show on textbox "Active Mode" instead of "Active" and so on. Is it possible to do that? It would be great if I could acomplish that in XAML - because all bindings I have in style file style.xaml

I was trying to use Description attributes but it seems that it's not enough

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

草莓味的萝莉 2024-09-26 00:32:18

恕我直言,使用转换器是更好的方法。

您应该做的第一件事是实现一个简单的属性,以便向枚举元素添加一些元数据。下面是一个基本示例(为了简单起见,没有国际化):

    public enum StepStatus {
    [StringValue("Not done yet")]
    NotDone,
    [StringValue("In progress")]
    InProgress,
    [StringValue("Failed")]
    Failed,
    [StringValue("Succeeded")]
    Succeeded
}

接下来,您可以编写一个实用程序类,能够使用反射将枚举元素转换为其相应的 StringValue 表示形式。在 Google 中搜索“C# 中的字符串枚举 - CodeProject”,您将找到 CodeProject 的相关文章(抱歉,我的低声誉不允许我添加链接..)

现在您可以实现一个转换器,只需将转换委托给实用程序类:

    [ValueConversion(typeof(StepStatus), typeof(String))]
public class StepStatusToStringConverter: IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture){
        String retVal = String.Empty;

        if (value != null && value is StepStatus) {
            retVal = StringEnum.GetStringValue((StepStatus)value);
        }

        return retVal;
    }

    /// <summary>
    /// ConvertBack value from binding back to source object. This isn't supported.
    /// </summary>
    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture) {
        throw new Exception("Can't convert back");
    }
}

最后,您可以在 XAML 代码中使用转换器:

<resourceWizardConverters:StepStatusToStringConverter x:Key="stepStatusToStringConverter" />
...
<TextBox Text="{Binding Path=ResourceCreationRequest.ResourceCreationResults.ResourceCreation, Converter={StaticResource stepStatusToStringConverter}}" ... />

检查以下页面< /a>;它给出了一个支持国际化的例子,但基本上原理是一样的。

IMHO, using a converter is a better approach.

The first thing you should do is implement a simple attribute in order to add some metadata to your enum elements. Here's a basic example (without internationalization for simplicity):

    public enum StepStatus {
    [StringValue("Not done yet")]
    NotDone,
    [StringValue("In progress")]
    InProgress,
    [StringValue("Failed")]
    Failed,
    [StringValue("Succeeded")]
    Succeeded
}

Next to that, you can write a utility class able to convert from an enum element to its corresponding StringValue representation using reflection. Search in Google for "String Enumerations in C# - CodeProject" and you'll find CodeProject's article about this (sorry, my low reputation won't let me add the link..)

Now you can implement a converter that simply delegates the conversion to the utility class:

    [ValueConversion(typeof(StepStatus), typeof(String))]
public class StepStatusToStringConverter: IValueConverter {
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture){
        String retVal = String.Empty;

        if (value != null && value is StepStatus) {
            retVal = StringEnum.GetStringValue((StepStatus)value);
        }

        return retVal;
    }

    /// <summary>
    /// ConvertBack value from binding back to source object. This isn't supported.
    /// </summary>
    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture) {
        throw new Exception("Can't convert back");
    }
}

Finally, you can use the converter in your XAML code:

<resourceWizardConverters:StepStatusToStringConverter x:Key="stepStatusToStringConverter" />
...
<TextBox Text="{Binding Path=ResourceCreationRequest.ResourceCreationResults.ResourceCreation, Converter={StaticResource stepStatusToStringConverter}}" ... />

Check the following page; it gives an example that supports internationalization, but basically the principle is the same..

雾里花 2024-09-26 00:32:18

对于这个简单的情况,您不需要转换器。请改用 Stringformat。前导“{}”是一个转义序列,用于告诉解析器您不打算将它们用于另一个嵌套标记。如果您在绑定文本(由“{0}”指示)之前添加文本,则可以将其删除。

<Window x:Class="TextBoxBoundToEnumSpike.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox Text="{Binding ModeEnum,StringFormat={}{0} Mode}"/>
        <Button Click="Button_Click" Height=" 50">
            Change to 'Selected'
        </Button>
    </StackPanel>
</Window>

using System.ComponentModel;
using System.Windows;

namespace TextBoxBoundToEnumSpike
{

    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        private ModeEnum m_modeEnum;
        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;
            ModeEnum = ModeEnum.ActiveAndSelected;
        }

        public ModeEnum ModeEnum
        {
            set
            {
                m_modeEnum = value;
                if (PropertyChanged!=null)PropertyChanged(this,new PropertyChangedEventArgs("ModeEnum"));
            }
            get { return m_modeEnum; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ModeEnum = ModeEnum.Selected;
        }
    }

    public  enum ModeEnum
    {
        Active,
        Selected,
        ActiveAndSelected
    }
}

You do not need a converter for this simple case. Use Stringformat in stead. The leading '{}' are an escape sequence to tell the parser that you do not mean to use them for another nested tag. If you add text before the bound text (indicated by '{0}'), you can remove them.

<Window x:Class="TextBoxBoundToEnumSpike.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox Text="{Binding ModeEnum,StringFormat={}{0} Mode}"/>
        <Button Click="Button_Click" Height=" 50">
            Change to 'Selected'
        </Button>
    </StackPanel>
</Window>

using System.ComponentModel;
using System.Windows;

namespace TextBoxBoundToEnumSpike
{

    public partial class MainWindow : Window,INotifyPropertyChanged
    {
        private ModeEnum m_modeEnum;
        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;
            ModeEnum = ModeEnum.ActiveAndSelected;
        }

        public ModeEnum ModeEnum
        {
            set
            {
                m_modeEnum = value;
                if (PropertyChanged!=null)PropertyChanged(this,new PropertyChangedEventArgs("ModeEnum"));
            }
            get { return m_modeEnum; }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ModeEnum = ModeEnum.Selected;
        }
    }

    public  enum ModeEnum
    {
        Active,
        Selected,
        ActiveAndSelected
    }
}
懵少女 2024-09-26 00:32:18

您可以使用转换器来执行此操作。通常绑定到枚举,但向绑定添加 Converter 属性。该转换器是一个实现 IValueConverter 的类,它将由 WPF 调用。在那里,您可以添加“Mode”之类的后缀(或做任何您喜欢的事情)。

You can use a Converter to do this. Bind to the enum normally but add a Converter property to the binding. The converter is a class implementing IValueConverter, which will be called by WPF. There, you can add a suffix like "Mode" (or do whatever you like).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文