WPF Combobox displays hierarchical data

I have a category table in my database as shown below.

Category

  • categoryId
  • name
  • Parentid

parentId refers to itself to form a hierarchy.

How do I bind it to combobox in WPF so that children are indented for each level?

+5
source share
1 answer

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>

WITH#:

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();
}

One must have the properties int Leveland string Namein your classroom

+7
source

All Articles