I am trying to bind a ComboBox, which have two categories (Letters and Numbers), to a Listbox.
Here is the C# Code:
class LibraryViewModel
{
public LetterOrNumberList lib { get; }
public LibraryViewModel()
{
lib = new LetterOrNumberList();
}
}
public class LetterOrNumberList : ObservableCollection<LettersAndNumbers>
{
public LetterOrNumberList()
{
LettersAndNumbers Letters = new LettersAndNumbers();
Letters.Title = "Letters";
ObservableCollection<IExample> letters = new ObservableCollection<IExample>();
letters.Add(new LetterA());
letters.Add(new LetterB());
Letters.LetterOrNumber = letters;
LettersAndNumbers Numbers = new LettersAndNumbers();
Numbers.Title = "Numbers";
ObservableCollection<IExample> numbers = new ObservableCollection<IExample>();
numbers.Add(new Number1());
numbers.Add(new Number2());
Numbers.LetterOrNumber = numbers;
this.Add(Letters);
this.Add(Numbers);
}
}
public class LettersAndNumbers
{
public string Title { get; set; }
public ObservableCollection<IExample> LetterOrNumber { get; set; }
}
public class LetterA : PropertyChangeClass, IExample
{
public string value
{
get
{
return _value;
}
set
{
_value = value;
OnPropertyChanged(nameof(value));
}
}
public LetterA()
{
value = "A";
}
private string _value;
}
public class LetterB : PropertyChangeClass, IExample
{
//principial the same like class Letter A
//...
}
public class Number1 : PropertyChangeClass, IExample
{
//principial the same like class Letter A
//...
}
public class Number2 : PropertyChangeClass, IExample
{
//principial the same like class Letter A
//...
}
public class PropertyChangeClass
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}
public interface IExample
{
string value { get; set; }
}
And in XAML I tried it as following:
<ComboBox Width="100" Name="cBox" Text="Bitte auswählen" ItemsSource="{Binding lib}" DisplayMemberPath="Title"/>
<ListBox Grid.Row="2" ItemsSource="{Binding cBox}" DisplayMemberPath="value"/>
The ComboBox binding works but I dont know how to bind the nested "value" property in dependency of the selecteditem.
Maybe someone know how to solve. Thanks!
EDIT:
I've a library of different products. Each product is to a category assigned. At the end the user should select a category and the products of it will be dynamically displayed (in a ListBox). I ve sorted it in a observablecollection that Ive the same structure like the code above.