WPF Combobox显示分层数据

Ada*_*ley 5 c# wpf binding

我的数据库中有一个类别表,如下所示.

类别

  • 的categoryId
  • 名称
  • parentId的

parentId链接回自身以形成层次结构.

如何将它绑定到WPF中的组合框,以便子元素适合每个级别缩进?

Myk*_*iuk 7

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>
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

一定要在班上有int Level和string Name属性