I have set a ListBox.ItemsSource to an ObservableCollection of custom class and the DataTemplate represents the data as ComboBoxes. When the ObservableCollection gets an item added, a new ComboBox gets created inside the ListBox, and if I change a value inside the ObservableCollection the connected ComboBox gets its value updated. However, if I change the ComboBoxes' values nothing happens inside the ObservableCollection. I have set the value binding of the ComboBox to
SelectedItem="{Binding Path=., Mode=TwoWay}"
So in short, I'm trying to connect ComboBoxes to a value inside a list, so that when I change the ComboBox.SelectedItem, the right value is changed inside the list and vice versa. The problem is that the values inside the list don't get updated when the ComboBox.SelectedItem gets changed.
xaml:
<ListBox x:Name="ContainerList" Margin="5,0,5,0" Width="140">
<ListBox.ItemTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MainWindow}},Path=TestEnums}"
SelectedItem="{Binding Path=., Mode=TwoWay}"
>
</ComboBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="MoreButton" Content="More" Click="AddContainerClass_Click"/>
Code behind:
public partial class MainWindow : Window
{
public enum TestEnum
{
value0,
value1,
value2,
value3,
value4,
}
public class ContainerClass
{
public ObservableCollection<TestEnum> Enums { get; set; }
public ContainerClass()
{
Enums = new ObservableCollection<TestEnum>();
}
}
public IEnumerable TestEnums { get; set; }
public ContainerClass Container { get; set; }
public MainWindow()
{
TestEnums = Enum.GetValues(typeof(TestEnum)).Cast<TestEnum>();
InitializeComponent();
Container = new ContainerClass();
ContainerList.ItemsSource = Container.Enums;
MoreButton.DataContext = Container;
}
private void AddContainerClass_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
ContainerClass cc = b.DataContext as ContainerClass;
cc.Enums.Add(TestEnum.value0);
}
}
ComboBox
? You also should state the complete type of theTestEnums
property. – Petr Vávro