C
C#7d ago
Tiranozavr

WPF: Binding selected item of ComboBox inside ItemsControl

Hello, I'm currently exploring WPF and kinda stuck with one particular case. I have ItemsControl with ItemTemplate being a ComboBox:
<ItemsControl ItemsSource="{Binding Values}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ComboBox Width="150"
ItemsSource="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType=Window}}"
SelectedItem="{Binding .}">
</ComboBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl ItemsSource="{Binding Values}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ComboBox Width="150"
ItemsSource="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType=Window}}"
SelectedItem="{Binding .}">
</ComboBox>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Values is a collection in my view model: public ObservableCollection<ComboBoxItemModel> Values { get; set; }; ItemsSource for comboboxes is a fixed List<ComboBoxItemModel> I can add and remove items and this changes will be reflected in my view: comboboxes will be added and removed. But if I change selected item in a combobox, this won't do anything with the collection. I've figured out I can create a wrapper class:
public class Wrapper
{
public ComboBoxItemModel Model {get; set; }
}
public class Wrapper
{
public ComboBoxItemModel Model {get; set; }
}
And change Values to be a collection of type Wrapper and update my binding to be: SelectedItem="{Binding Model}" This way changing selected item of any combobox will update Model field of corresponding Wrapper object in my collection. So far so good, but it seems kinda hacky. Am I doing it right? Is the Wrapper class mandatory in this case?
1 Reply
obason
obason11h ago
ViewModel class have to implement INotifyPropertyChanged to reflect data change to View> https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-property-change-notification?view=netframeworkdesktop-4.8
How to: Implement Property Change Notification - WPF .NET Framework
Enable your properties to automatically notify a binding source when the property value changes in Windows Presentation Foundation (WPF).
Want results from more Discord servers?
Add your server