开发者

WPF Combobox displaying hierarchical data

I 开发者_JAVA技巧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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜