2017-04-06 76 views
0

我有一個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; } 
} 
+0

檢查'dg'是否爲空? – AnjumSKhan

+1

投票結束,因爲沒有足夠的信息來重現問題。如果有人知道在給定這段代碼的情況下發生了什麼? – grek40

+0

對不起,我不知道什麼是有用的。代碼非常複雜。 –

回答

0

更改綁定模式來OneWay,那麼它的工作。

相關問題