Reputation: 1494
I have a collection of items, say:
class Myclass : INotifyPropertyChanged
{
public bool Selected { get; set; }
public string ChosenValue { get; set; }
}
I then have an observable collection of this class:
public ObservableCollection<Myclass> _myObColl
Finally I have a list box that is bound to _myObColl
and a separate combobox that is bound to another collection.
I want updating the combobox to update the ChosenValue property of all the items in _myObColl
list. But I can't figure out how.
The combo box selected item is bound to a property in the viewmodel called currselection. What I want to do is bind the ChosenValue property of Myclass to the currselection value. But how do I do this? Maybe I shouldn't be thinking of binding but I can't think of another way to update the items ChosenValue property. I tried the SelectionChanged
event of the combo to loop through _myObColl
. This works except if an item is marked selected after the combobox is changed.
<ComboBox ItemsSource="{Binding Path=DataContext.lstComboList , ElementName=PS4}" SelectedItem="{Binding Path=currselection, Mode=TwoWay}" Margin="10,10,10,10" Width="100"/>
<ListBox ItemsSource="{Binding _myObColl}" Margin="10,10,0,0" >
<ListBox.ItemTemplate x:Uid="asdasd" >
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<CheckBox Grid.Column ="3" Width="50" VerticalAlignment="Center" Margin="10" IsChecked="{Binding Path=PropA, Mode=TwoWay}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Upvotes: 0
Views: 43
Reputation: 2224
If you want the combo box to change the value of the selected item in the listbox you could bind the the SelectedItem like this.
<ComboBox ItemsSource="{Binding ComboList}" SelectedItem="{Binding ElementName=listBox, Path=SelectedItem.ChosenValue}" />
Otherwise if you really want to change the property of all the items in the list when the combo box changes you would need to do it in code behind, in the property setter.
<ComboBox ItemsSource="{Binding ComboList}" SelectedItem="{Binding SelectedValue}"/>
In ViewModel
private string _SelectedValue;
public string SelectedValue
{
get => _SelectedValue;
set
{
_SelectedValue = value;
foreach (var item in MyObColl.ToList()) item.ChosenValue = _SelectedValue;
}
}
Upvotes: 1