C# WPF MVVM可编辑组合框新值为空

C# WPF MVVM可编辑组合框新值为空,c#,wpf,mvvm,combobox,C#,Wpf,Mvvm,Combobox,尝试了所有类似问题的解决方案,仍然没有成功。我有一个组合框,用于选择现有项目和/或添加新项目。只有选定的项目零件有效。类别只是一个具有名称和Id的对象 提前谢谢 XAML <ComboBox Name="CbCategory" ItemsSource="{Binding Categories}" SelectedItem="{Binding SelectedCategory.Name, UpdateSourceTrigger=PropertyChanged}" Text="

尝试了所有类似问题的解决方案,仍然没有成功。我有一个
组合框
,用于选择现有项目和/或添加新项目。只有选定的项目零件有效。类别只是一个具有
名称
Id
的对象

提前谢谢

XAML

<ComboBox Name="CbCategory" ItemsSource="{Binding Categories}"
    SelectedItem="{Binding SelectedCategory.Name, UpdateSourceTrigger=PropertyChanged}"
    Text="{Binding NewCategory.Name}" DisplayMemberPath="Name" 
    IsEditable="True"/>

您的
文本
绑定不起作用,因为您是针对
null
类别
属性进行绑定的。而是实例化它

public Category NewCategory
{
    get { return _newCategory ?? (_newCategory = new Category()); }
    set
        {
          if (Equals(_newCategory, value)) return;
          _newCategory = value;
           SendPropertyChanged("NewCategory");
         }
}
编辑:根据您的评论详细说明:

您的
组合框.Text
绑定设置为
“{binding NewCategory.Name}”
,因此无论
SelectedCategory
的值是什么,
Text
属性将始终反映
NewCategory
的名称

NewCategory
为空时,
Text
属性没有要绑定的对象,因此无法执行双向绑定(即,
Text
属性的值不能传回
NewCategory.Name
,因为这将导致
NullReferenceException
(因为
NewCategory
为空)


这不影响
SelectedItem
的情况,因为它直接绑定到
SelectedCategory
属性,而不是该属性的子属性。

创建新变量以保留combobox的文本。如果SelectedItem具有null值,则将combobox的文本作为新项获取

代码:

<ComboBox Name="CbCategory" ItemsSource="{Binding Categories}"
    SelectedItem="{Binding SelectedCategory.Name, UpdateSourceTrigger=PropertyChanged}"
    Text="{Binding Name}" DisplayMemberPath="Name" 
    IsEditable="True"/>

private String _name;
public Category Name
{
    get { return _name; }

    set
    {        
         _name = value
         SendPropertyChanged("Name");
    }
}

public ICommand ItemChange
{
 get
 {
   `return new RelayCommand(() =>`{
                    try{string item = this.SelectedCategory.Code;}
catch(Exception ex){string item = this.Name;}
                }, () => { return true; });
            }
        }

私有字符串\u名称;
公共类别名称
{
获取{return\u name;}
设置
{        
_名称=值
SendPropertyChanged(“名称”);
}
}
公共ICommand项更改
{
得到
{
`返回新的RelayCommand(()=>`{
请尝试{string item=this.SelectedCategory.Code;}
catch(异常ex){string item=this.Name;}
},()=>{return true;});
}
}

whicked!它正在工作…但我只是想了解为什么?我的意思是,在selectedCategory中也没有实例化,但它工作了…请解释一下好吗?
<ComboBox Name="CbCategory" ItemsSource="{Binding Categories}"
    SelectedItem="{Binding SelectedCategory.Name, UpdateSourceTrigger=PropertyChanged}"
    Text="{Binding Name}" DisplayMemberPath="Name" 
    IsEditable="True"/>

private String _name;
public Category Name
{
    get { return _name; }

    set
    {        
         _name = value
         SendPropertyChanged("Name");
    }
}

public ICommand ItemChange
{
 get
 {
   `return new RelayCommand(() =>`{
                    try{string item = this.SelectedCategory.Code;}
catch(Exception ex){string item = this.Name;}
                }, () => { return true; });
            }
        }