I have a table of categories in my database, as below.
Category
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With