我遇到的问题是我尝试使用具有多项选择功能的DataGrid,并且我试图在不按Ctrl键的情况下选择多个
在我看来,我有:
<DataGrid Grid.Row="1" ItemsSource="{Binding Tags}" SelectionMode="Extended" SelectionUnit="FullRow" AutoGenerateColumns="False"
SelectedRows ="{Binding SelectedTags, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
CanUserAddRows="False">
<DataGrid.ItemContainerStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</DataGrid.ItemContainerStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<EventSetter Event="PreviewMouseDown" Handler="DataGridRowPreviewMouseDownHandler"></EventSetter>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn
Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=DataGridRow}, Mode = TwoWay}"
MaxWidth="25" MinWidth="25">
<DataGridCheckBoxColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</DataGridCheckBoxColumn.CellStyle>
</DataGridCheckBoxColumn>
</DataGrid.Columns>
</DataGrid>
在我的代码背后:
private void DataGridRowPreviewMouseDownHandler(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
var row = GetVisualParentByType((FrameworkElement)e.OriginalSource, typeof(DataGridRow)) as DataGridRow;
if (row != null)
{
row.IsSelected = !row.IsSelected;
e.Handled = true;
}
}
}
public static DependencyObject GetVisualParentByType(DependencyObject startObject, Type type)
{
DependencyObject parent = startObject;
while (parent != null)
{
if (type.IsInstanceOfType(parent))
break;
else
parent = VisualTreeHelper.GetParent(parent);
}
return parent;
}
我的模型类是
public class Tags : INotifyPropertyChanged
{
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set { _isSelected = value; RaisePropertyChanged("IsSelected"); }
}
public int ID { get; set; }
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
GridView的CataContext是一个ObservableCollection
问题在于我在DataGridRowPreviewMouseDownHandler中设置
row.IsSelected =!row.IsSelected;
模型未更新。
没有DataGridRowPreviewMouseDownHandler一切正常。有了它,初始绑定不起作用(例如,如果我在添加到ObservableCollection时将一个标签的IsSelected设置为true,它将显示为未选中)。知道为什么吗?
如何触发对行绑定对象的更新?