Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Combobox displaying hierarchical data

Tags:

c#

binding

wpf

I have a table of categories in my database, as below.

Category

  • categoryId
  • name
  • parentId

The parentId links back to itself to form hierarchy.

How do I bind it to a combobox in WPF so that the child elements are indented as appropriate for each level?

like image 615
Adam Avatar asked Dec 26 '10 15:12

Adam


1 Answers

XAML:

<ComboBox ItemsSource="{Binding YourItems}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Margin="{Binding Level, Converter={x:Static my:MainWindow.LevelToMarginConverter}}" Text="{Binding Name}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

C#:

class MainWindow {
    ......
    class LevelToMarginConverterClass : IValueConverter {
        const int onelevelmargin = 10;
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            int level = (int)value;
            return new Thickness(level * onelevelmargin,0,0,0);
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
            return null;
        }
    }
    public static IValueConverter LevelToMarginConverter = new LevelToMarginConverterClass();
}

Be sure to have int Level and string Name properties in your class

like image 122
Mykola Bogdiuk Avatar answered Sep 20 '22 12:09

Mykola Bogdiuk