Until now, to can know in the view model the selected items in a list view, I am using an attached property.
This is the code:
public class ListViewSelectedItemsBehavior : Behavior<ListView>
{
protected override void OnAttached()
{
AssociatedObject.SelectionChanged += AssociatedObjectSelectionChanged;
}
protected override void OnDetaching()
{
AssociatedObject.SelectionChanged -= AssociatedObjectSelectionChanged;
}
void AssociatedObjectSelectionChanged(object sender, SelectionChangedEventArgs e)
{
SelectedItems = new ObservableCollection<object>(AssociatedObject.SelectedItems.Cast<object>());
}
public ObservableCollection<object> SelectedItems
{
get { return (ObservableCollection<object>)GetValue(SelectedItemsProperty); }
set { SetValue(SelectedItemsProperty, value); }
}
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.Register("SelectedItems"
, typeof(ObservableCollection<object>)
, typeof(ListViewSelectedItemsBehavior)
,
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
}
The problem is that the ObservableCollection is of type object, but in the view model I need to work with a collection of the specific type that it needs. So I have to do something like that in the view model:
partial void OnMyCollectionSelectedItemsChanged(ObservableCollection<object> value)
{
_myCollectionSelectedItemsTyped!.Clear();
if (value != null) _myCollectionSelectedItemsTyped.AddRange(value.Cast<string>());
}
private List<string> _myCollectionSelectedItemsTyped = new List<string>();
I was thinking that if in the attached property I could do in some way to use a generic type or another way to avoid to have to add this code in the view models, it would be a good improvement. But really I don't know how could I do it.
Thanks.