public class ListBoxSelectedItemsAttachedProperty
{
#region SelectedItems
private static ListBox list;
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList),
typeof(ListBoxSelectedItemsAttachedProperty),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault
,new PropertyChangedCallback(OnSelectedItemsChanged)
));
public static IList GetSelectedItems(DependencyObject d)
{
return (IList)d.GetValue(SelectedItemsProperty);
}
public static void SetSelectedItems(DependencyObject d, IList value)
{
d.SetValue(SelectedItemsProperty, value);
}
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
ListBox listBox = (ListBox)d;
list = listBox;
listBox.SelectionChanged += listBox_SelectionChanged;
listBox.Unloaded += listBox_Unloaded;
}
private static void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
IEnumerable listBoxSelectedItems = list.SelectedItems;
IList ModelSelectedItems = GetSelectedItems(list);
ModelSelectedItems.Clear();
if (list.SelectedItems != null)
{
foreach (var item in list.SelectedItems)
ModelSelectedItems.Add(item);
}
SetSelectedItems(list, ModelSelectedItems);
}
private static void listBox_Unloaded(object sender, RoutedEventArgs e)
{
ListBox listBox = sender as ListBox;
listBox.SelectionChanged -= listBox_SelectionChanged;
listBox.Unloaded -= listBox_Unloaded;
}
#endregion
}
我的窗口中有两个列表框,以这种方式使用这个附加属性:
<ListBox HorizontalAlignment="Left" Margin="5,0,5,0" Name="lsbGenerosAsignados" VerticalAlignment="Stretch" Width="Auto" MinWidth="130" Grid.Column="2" Grid.Row="1"
SelectionMode="Extended"
ItemsSource="{Binding Collection1InViewModel}"
DisplayMemberPath="Name"
Behaviors:ListBoxSelectedItemsAttachedProperty.SelectedItems="{Binding Property1InViewModel}">
<ListBox HorizontalAlignment="Left" Margin="5,0,5,0" Name="lsbGenerosAsignados" VerticalAlignment="Stretch" Width="Auto" MinWidth="130" Grid.Column="2" Grid.Row="1"
SelectionMode="Extended"
ItemsSource="{Binding Collection2InViewModel}"
DisplayMemberPath="Name"
Behaviors:ListBoxSelectedItemsAttachedProperty.SelectedItems="{Binding Property2InViewModel}">
但是,当第一个列表框中的选择更改时,不会通知视图模型。如果我从第二个列表框中删除了取消附加的属性,那么它将按预期工作。
我如何将这个附加属性与两个listoBox一起使用,并通知视图模型属性?