views:

59

answers:

3

Hi 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

+1  A: 

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

Timores
Could You give me some example please ?
george dobravski
Yes, I could (see http://blogs.msdn.com/b/bencon/archive/2006/05/10/594886.aspx), but @Dabblernl's answer is better.
Timores
+2  A: 

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
    }
}
Dabblernl
A: 

Could You tell me how does it work ? I don't understand how this stringformat changes output

george dobravski