2017-04-06 11 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()を呼び出して、私はそれがnullではありません確認してください。

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()は、1行に異なる

於 System.Windows.Controls.DataGrid.UnselectAllCells() - >於 System.Windows.Controls.Primitives.MultiSelector.UnselectAll()

編集4

私がSelectedItemをバインドしないと、それは動作します。私はのSelectedItemを持っていないことができ、他の

SelectedItem="{Binding Item}"

。しかし、私はそれを縛る必要があります。

私のデータバインディングはどうなりますか?このような

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'がnullであることを確認しますか? – AnjumSKhan

+1

問題を再現するのに十分な情報がないため、投票を終了してください。この量のコードがあれば誰が何が起こっているのかを知っておくべきでしょうか? – grek40

+0

申し訳ありませんが、私は何が役に立つのか分かりません。コードは非常に複雑です。 –

答えて

0

私はそれが仕事だ、OneWayへの結合モードを変更します。

関連する問題