我有一个DataGrid,包含扩展器。wpf为什么在绑定SelectedItem时得到“NullReferenceException”[编辑]
我想在扩展器单击时取消选择所有行,所以我打电话给dg.UnSelectAll()
或dg.UnSelectAllCells()
。
但是,总是得到NullReferenceException。
我不知道发生了什么事。
编辑:
我的DataGrid中做一些事情,包括一些样式代码。
的XAML
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<!--<Expander IsExpanded="{Binding Mode=TwoWay, Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}, Mode=FindAncestor}}" MouseRightButtonDown="Expander_MouseRightButtonDown">-->
<Expander IsExpanded="False" MouseRightButtonDown="Expander_MouseRightButtonDown"
Background="Gainsboro" ButtonBase.Click="Expander_Click">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="Gray" FontSize="16" VerticalAlignment="Bottom"/>
<TextBlock Text="{Binding ItemCount}" Foreground="Green" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
<TextBlock Text=" item(s)" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter/>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataGrid Name="dg" ItemsSource="{Binding GroupView}" SelectedIndex="{Binding Index}" SelectedItem="{Binding Item}" SelectionChanged="SelectionChanged"
AutoGenerateColumns="False" CanUserAddRows="False"
CanUserResizeColumns="False" CanUserResizeRows="False"
CanUserSortColumns="False"
IsReadOnly="True"
FontWeight="Bold"
RowHeaderWidth="0"
GridLinesVisibility="Horizontal" HorizontalGridLinesBrush="White">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="BorderThickness" Value="0"/>
<!-- Remove the focus indication for the selected cell -->
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
</Style>
</DataGrid.CellStyle>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="BorderThickness" Value="3"/>
<Setter Property="BorderBrush" Value="White"/>
<Setter Property="Background" Value="LightGray"/>
<Setter Property="Foreground" Value="DimGray"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" Value="WhiteSmoke"/>
<Setter Property="FontFamily" Value="Microsoft Sans Serif"/>
<Setter Property="FontWeight" Value="Bold"/>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Sign" MinWidth="100" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Ellipse Width="20" Height="20" Fill="LightGray"/>
<Ellipse Width="16" Height="16" Fill="DimGray"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn MinWidth="100" Width="Auto" Header="No." Binding="{Binding Age}" Foreground="Peru"/>
<DataGridTextColumn MinWidth="200" Width="Auto" Header="Command Name" Binding="{Binding Name}" Foreground="LimeGreen"/>
</DataGrid.Columns>
<DataGrid.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
编辑2
我打电话UnSelectedAll()
扩展点击的时候,我检查它不为空。
private void Expander_Click(object sender, RoutedEventArgs e)
{
try
{
if (dg != null && dg.SelectedIndex != -1)
dg.UnselectAll();
}
catch (Exception ex)
{
MessageBox.Show(string.Format("{0}, {1}", ex.StackTrace.ToString(), ex.ToString()));
}
}
编辑3
使用UnSelectedAllCells()
,我赶上这样的:
---------------------------
---------------------------
於 MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid(Object item)
於 MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid()
於 MS.Internal.Data.PropertyPathWorker.get_IsDBNullValidForUpdate()
於 MS.Internal.Data.ClrBindingWorker.get_IsDBNullValidForUpdate()
於 System.Windows.Data.BindingExpression.ConvertProposedValue(Object value)
於 System.Windows.Data.BindingExpressionBase.UpdateValue()
於 System.Windows.Data.BindingExpression.UpdateOverride()
於 System.Windows.Data.BindingExpressionBase.Update()
於 System.Windows.Data.BindingExpressionBase.ProcessDirty()
於 System.Windows.Data.BindingExpressionBase.Dirty()
於 System.Windows.Data.BindingExpressionBase.SetValue(DependencyObject d, DependencyProperty dp, Object value)
於 System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
於 System.Windows.DependencyObject.SetCurrentValueInternal(DependencyProperty dp, Object value)
於 System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties()
於 System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
於 System.Windows.Controls.Primitives.Selector.UnselectAllImpl()
於 System.Windows.Controls.DataGrid.UnselectAllCells()
於 SList.Expander_Click(Object sender, RoutedEventArgs e) 於 D:\SList.xaml.cs: 行 123, System.NullReferenceException: 並未將物件參考設定為物件的執行個體。
於 MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid(Object item)
於 MS.Internal.Data.PropertyPathWorker.DetermineWhetherDBNullIsValid()
於 MS.Internal.Data.PropertyPathWorker.get_IsDBNullValidForUpdate()
於 MS.Internal.Data.ClrBindingWorker.get_IsDBNullValidForUpdate()
於 System.Windows.Data.BindingExpression.ConvertProposedValue(Object value)
於 System.Windows.Data.BindingExpressionBase.UpdateValue()
於 System.Windows.Data.BindingExpression.UpdateOverride()
於 System.Windows.Data.BindingExpressionBase.Update()
於 System.Windows.Data.BindingExpressionBase.ProcessDirty()
於 System.Windows.Data.BindingExpressionBase.Dirty()
於 System.Windows.Data.BindingExpressionBase.SetValue(DependencyObject d, DependencyProperty dp, Object value)
於 System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
於 System.Windows.DependencyObject.SetCurrentValueInternal(DependencyProperty dp, Object value)
於 System.Windows.Controls.Primitives.Selector.UpdatePublicSelectionProperties()
於 System.Windows.Controls.Primitives.Selector.SelectionChanger.End()
於 System.Windows.Controls.Primitives.Selector.UnselectAllImpl()
於 System.Windows.Controls.DataGrid.UnselectAllCells()
於 SList.Expander_Click(Object sender, RoutedEventArgs e) 於 D:\SList.xaml.cs: 行 123
---------------------------
確定
---------------------------
UnSelectedAll()
不同的是在一行
於 System.Windows.Controls.DataGrid.UnselectAllCells()
- >於 System.Windows.Controls.Primitives.MultiSelector.UnselectAll()
编辑4
如果我不绑定SelectedItem,它的工作!
SelectedItem="{Binding Item}"
别的我不能得到的SelectedItem。但我需要绑定它。
我的数据绑定发生了什么?
VM是这样的:
public class TestVM : INotifyPropertyChanged
{
private int _index;
public int Index
{
get
{
return _index;
}
set
{
_index = value;
RaisePropertyChanged("Index");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(String propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
private User _item;
public User Item
{
get
{
return _item;
}
set
{
_item = value;
RaisePropertyChanged("Item");
}
}
private string _selectedGroup;
public string SelectedGroup
{
get
{
return _selectedGroup;
}
set
{
_selectedGroup = value;
RaisePropertyChanged("SelectedGroup");
}
}
ObservableCollection<User> _collection;
public ObservableCollection<User> Collection
{
get
{
return _collection;
}
private set
{
_collection = value;
RaisePropertyChanged("Collection");
}
}
ListCollectionView _groupView;
public ListCollectionView GroupView
{
get
{
return _groupView;
}
private set
{
_groupView = value;
RaisePropertyChanged("GroupView");
}
}
public TestVM()
{
Collection = new ObservableCollection<User>();
Collection.Add(new User() { Name = "John Doe1", Age = 10, group = "Group 1" });
Collection.Add(new User() { Name = "Jane Doe2", Age = 20, group = "Group 1" });
Collection.Add(new User() { Name = "Sammy Doe", Age = 30, group = "Group 2" });
Collection.Add(new User() { Name = "Sammy Doe1", Age = 40, group = "Group 2" });
Collection.Add(new User() { Name = "Sammy Doe2", Age = 50, group = "Group 2" });
Collection.Add(new User() { Name = "Sammy Doe3", Age = 60, group = "Group 3" });
Collection.Add(new User() { Name = "Sammy Doe4", Age = 70, group = "Group 3" });
Collection.Add(new User() { Name = "Sammy Doe5", Age = 80, group = "Group 3" });
Collection.Add(new User() { Name = "Sammy Doe6", Age = 90, group = "Group 4" });
Collection.Add(new User() { Name = "Sammy Doe7", Age = 10, group = "Group 4" });
GroupView = new ListCollectionView(Collection);
GroupView.GroupDescriptions.Add(new PropertyGroupDescription("group"));
}
}
public class User
{
public string Name { set; get; }
public int Age { set; get; }
public string group { get; set; }
}
检查'dg'是否为空? – AnjumSKhan
投票结束,因为没有足够的信息来重现问题。如果有人知道在给定这段代码的情况下发生了什么? – grek40
对不起,我不知道什么是有用的。代码非常复杂。 –