CodeCopy

October 6, 2009

WPF Databinding Enum with nice descriptions

Filed under: c#,wpf — sterndorff @ 17:28
Tags: , , ,

I have an Enum that I want to databind to a wpf drop down box. But I want to represent the enum with some nice descriptions instead of Enum.ToString().

1) The enum with the nice descriptions: MyEnum.cs

    public enum MyEnum
    {
        [Description("Default value")] // Default value if enum is nullable and used in databinding
        DefaultValue,
        [Description("Value1 description")]
        Value1,
        [Description("Value2 description")]
        Value2
    }

(more…)

September 10, 2009

Implicit Two Way binding

Filed under: c#,wpf — mazzoo @ 19:12
Tags: , , ,

If you try to use TwoWay binding directly on for example a textbox in a listbox. You will have a problem.

<ListBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding ListOfStrings}">
   <ListBox.ItemTemplate>
       <DataTemplate>
          <TextBox Text="{Binding}"/>
       </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

The result you want is obvious, you want to allow the TextBox manipulate the ListOfStrings ( oftype List<string> ).

The error you will get will look something like: Two-way binding requires Path or XPath.

The solution is this, it’s not pretty but it works !

<ListBox Grid.Column="1" Grid.Row="1" ItemsSource="{Binding ListOfStrings}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBox Text="{Binding Path=DataContext, RelativeSource={RelativeSource Self}}"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

Theme: Rubric. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.