WPF DataGrid ComboBoxColumn没有插入值

时间:2011-04-25 15:18:41

标签: wpf datagrid binding datagridcomboboxcolumn

我有一个带有组合框列和两个文本框列的WPF数据网格。在我的测试用例中,当加载屏幕时,集合中有两行绑定网格。如果我更改任何单元格的内容,它会正确更新。但是,如果我向网格添加新行,当我更新组合框列中的值时,它不会在源集合中更新。尽管文本框列适用于新添加的行。列定义如下:

<DataGrid.Columns>
    <DataGridComboBoxColumn Header="Type" Width="*" SelectedValueBinding="{Binding Mode=TwoWay, Path=Type.Id}"
       ItemsSource="{Binding Source={StaticResource PhoneTypeList}, Path=PhoneTypes}"
       SelectedValuePath="Id" DisplayMemberPath="Type" />
    <DataGridTextColumn Binding="{Binding NotifyOnTargetUpdated=True, Path=Number, Mode=TwoWay, ValidatesOnExceptions=False}" Header="Number" Width="*"/>
    <DataGridTextColumn Binding="{Binding NotifyOnSourceUpdated=True, Path=Extension, ValidatesOnExceptions=False}" Header="Extension" Width="*"/>
</DataGrid.Columns>

以下是我的viewmodel中的PhoneNumbers属性:

public ObservableCollection<PhoneNumber> PhoneNumbers
        {
            get
            {
                return _phoneNumbers;
            }
            set
            {
                if (value != _phoneNumbers)
                {
                    _phoneNumbers = value;
                    OnPropertyChanged("PhoneNumbers");
                }
            }
        }

更新:这是我的PhoneNumber课程:

public class PhoneNumber : INotifyPropertyChanged
    {
        private string _number;
        private string _extension;
        private PhoneType _type;

        public PhoneType Type { get { return _type; }
            set { _type = value; OnPropertyChanged("Type"); } }
        public string Number
        {
            set
            {
                _number = value;
                OnPropertyChanged("Number");
            }
            get { return _number; }
        }

        public string Extension
        {
            set
            {
                _extension = value;
                OnPropertyChanged("Extension");
            }
            get { return _extension; }
        }

        public override string ToString()
        {
            return Number + (!string.IsNullOrEmpty(Extension) ? " x " + Extension : "");
        }

        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this,
                    new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }

1 个答案:

答案 0 :(得分:0)

首先,检查输出窗口是否有任何绑定错误消息。

在我看来,在添加新项目时,Type属性可能为null。这实质上使得Type的Id属性不可访问。

尝试在PhoneNumber构造函数中实例化一个新的默认Type对象

PhoneNumber() 
{
    _type = new PhoneType();
}

或者更好的是,将组合框直接绑定到类型而不是嵌套的Type.Id(更改SelectedValue绑定并删除SelectedValuePath。

<DataGridComboBoxColumn Header="Type" Width="*" SelectedValueBinding="{Binding Mode=TwoWay, Path=Type}"
   ItemsSource="{Binding Source={StaticResource PhoneTypeList}, Path=PhoneTypes}"
   DisplayMemberPath="Type" />