wpf为什么会得到“ NullReferenceException”绑定SelectedItem时[编辑] [英] wpf why get "NullReferenceException" when binding SelectedItem [Edit]

查看:93
本文介绍了wpf为什么会得到“ NullReferenceException”绑定SelectedItem时[编辑]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGrid,包括扩展器。

I had a DataGrid, include expander.

我想在扩展器单击时取消选择所有行,所以我调用 dg.UnSelectAll() dg.UnSelectAllCells()

I want to unselect all rows when expander click, so I call dg.UnSelectAll() or dg.UnSelectAllCells().

但是,始终获取NullReferenceException。

But, always get NullReferenceException.

我不知道发生了什么。

编辑:

我的DataGrid做一些事情,包括一些样式代码。

My DataGrid Do something, include some style code.

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(),并且检查它是否不为空。

I call UnSelectedAll() when expander click, and I check it's not 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()一行不同

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

编辑4

如果我不绑定SelectedItem,那就行了!

If I don't bind SelectedItem, it's work!

SelectedItem = {Binding Item}

否则我无法得到了SelectedItem。但是我需要绑定它。

else I can't got SelectedItem. But I need binding it.

我的数据绑定发生了什么事?

What happening on my data-binding?

VM像这样: p>

VM like this:

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; }
}


推荐答案

我将绑定模式更改为 OneWay ,就可以了。

I change Binding Mode to OneWay, then it's work.

这篇关于wpf为什么会得到“ NullReferenceException”绑定SelectedItem时[编辑]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆