Binding enum type to textbox

12,043

Solution 1

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..

Solution 2

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
    }
}

Solution 3

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).

Share:
12,043
george dobravski
Author by

george dobravski

Updated on June 04, 2022

Comments

  • george dobravski
    george dobravski almost 2 years

    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