我想将SelectedItems
的{{1}}绑定到我的视图模型。我在我的XAML中使用了这个附加属性和代码。
附属物:
DataGrid
XAML:
public class DataGridSelectedItemsAttachedPropertyV2
{
#region SelectedItems
///
/// SelectedItems Attached Dependency Property
///
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList),
typeof(DataGridSelectedItemsAttachedPropertyV2),
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)
{
DataGrid miDg = d as DataGrid;
IList ModelSelectedItems = GetSelectedItems(miDg);
if (miDg.SelectedItems != null)
{
foreach (var item in miDg.SelectedItems)
ModelSelectedItems.Add(item);
}
SetSelectedItems(miDg, ModelSelectedItems);
}
#endregion
}
代码得到了这一点:
<DataGrid AutoGenerateColumns="False" HorizontalAlignment="Stretch" Margin="5,5,0,12" Name="dgdGeneros" VerticalAlignment="Stretch" Grid.Row="1"
Behaviors:DataGridSelectedItemsAttachedPropertyV2.SelectedItems="{Binding DgdOrigenesSelectedItems}">
但是当我在public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList),
typeof(DataGridSelectedItemsAttachedPropertyV2),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(OnSelectedItemsChanged)));
中选择一个项目时,它永远不会进入OnSelectedItemsChanged()
方法,但我无法看到问题。
感谢。