Reputation: 149
So I have a list of all possible values, and a list of occurring values, that occurs only once. Like [A, B, C, D, E] and [D, A], each element of the second list must be a member of the first as well.
I want to create a listview with one row per possible value, where each row is a checkbox, binding the content to the name of the value and IsChecked to something like occuringValues.contains(possibleValue). In my example this would look like:
[x] A
[ ] B
[ ] C
[x] D
[ ] E
Checking or unchecking a checkbox should add or remove an element from the occurring values list.
I've tried a number of approaches without much luck, like:
Creating a INotifyPropertyChanged-implementing helper class with a string and a bool (for IsChecked) and an ObservableCollection gives me control over the changes in my class, but changes in the class does not trigger my set function for the ObservableCollection, otherwise I could have updated my [D, A] list there.
I could change my GUI to make things easier, listing the occuringValues and making a comboBox with possibleValues, but I'd prefer to use checkboxes, if you have an idea for me.
Upvotes: 2
Views: 3413
Reputation: 149
So I managed to solve this in a way inspired by Andrews suggestion.
I added a wrapper class like this:
class MyOccExpLimitComment
{
private ObservableCollection<OccupationalExposureLimitComment> Occuring;
public MyOccExpLimitComment(ObservableCollection<OccupationalExposureLimitComment> occuring, OccupationalExposureLimitComment inner)
{
Occuring = occuring;
Inner = inner;
}
public OccupationalExposureLimitComment Inner { get; set; }
public bool IsChecked
{
get
{
return Occuring.Contains(Inner);
}
set
{
if (value == false)
{
if (Occuring.Contains(Inner))
Occuring.Remove(Inner);
}
else
if (!Occuring.Contains(Inner))
Occuring.Add(Inner);
}
}
}
XAML:
<ListView ItemsSource="{Binding Path=MyOccExpLimitComments}" Grid.ColumnSpan="3" Grid.Column="0" HorizontalAlignment="Left" Height="153" Margin="2,2,0,0" Grid.Row="8" VerticalAlignment="Top" Width="296">
<ListView.View>
<GridView>
<GridViewColumn Width="269">
<GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}" Content="{Binding Inner.Title_SV}"/>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
Property:
private ObservableCollection<MyOccExpLimitComment> myOccExpLimitComments;
public ObservableCollection<MyOccExpLimitComment> MyOccExpLimitComments
{
get
{
if (myOccExpLimitComments == null)
myOccExpLimitComments = new ObservableCollection<MyOccExpLimitComment>(AvailableOccExpLimitComments.Select(c => new MyOccExpLimitComment(OccExpLimitComments, c)));
return myOccExpLimitComments;
}
}
So every element in my collection is aware of its existence in the collection through the Occuring reference to the collection, and uses the setter to update the collection when the boxes are checked/unchecked.
Upvotes: 2