C# MVVM组合框绑定并添加到组合框
嗨,我想做一个绑定MVVM组合框,我可以在组合框中添加我想从程序而不是源代码中添加的任何名称。 我尝试了一些东西,但是当我打开组合框的时候,我看到了这个 这是程序中的代码,我不知道出了什么问题,对我来说它看起来很好 型号:C# MVVM组合框绑定并添加到组合框,c#,wpf,mvvm,C#,Wpf,Mvvm,嗨,我想做一个绑定MVVM组合框,我可以在组合框中添加我想从程序而不是源代码中添加的任何名称。 我尝试了一些东西,但是当我打开组合框的时候,我看到了这个 这是程序中的代码,我不知道出了什么问题,对我来说它看起来很好 型号: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace PowerTol
{
public class Parts : Changed
{
public string name;
public string Name
{
get { return name; }
set
{
if(name != null)
{
name = value;
RaisePropertyChanged("Name");
}
}
}
}
}
视图模型:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Collections.ObjectModel;
namespace WpfApp1
{
public class AddViewModel : Changed
{
private ObservableCollection<Parts> _persons;
public AddViewModel()
{
Persons = new ObservableCollection<Parts>()
{
new Parts{Name="Nirav"}
,new Parts{Name="Kapil"}
,new Parts{Name="Arvind"}
,new Parts{Name="Rajan"}
};
}
public ObservableCollection<Parts> Persons
{
get { return _persons; }
set { _persons = value; }
}
private Parts _sperson;
public Parts SPerson
{
get { return _sperson; }
set { _sperson = value; }
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用系统组件模型;
使用System.Collections.ObjectModel;
命名空间WpfApp1
{
公共类AddViewModel:已更改
{
私人可观察收集人;
公共AddViewModel()
{
人员=新观察到的集合()
{
新零件{Name=“Nirav”}
,新零件{Name=“Kapil”}
,新零件{Name=“Arvind”}
,新零件{Name=“Rajan”}
};
}
公众人士
{
获取{return\u persons;}
设置{u persons=value;}
}
私人零件;
公共零件销售员
{
获取{return\u sperson;}
设置{u sperson=value;}
}
}
}
组合框:
<Grid>
<ComboBox ItemsSource="{Binding Persons}" SelectedItem="{Binding Path=SPersons}" HorizontalAlignment="Left" Margin="208,135,0,0" VerticalAlignment="Top" Width="314" Height="27">
</ComboBox>
</Grid>
尝试将DisplayMemberPath=“Name”
放入组合框中。现在,您将对象作为源提供,而应用程序不知道要显示什么,因此它显示类型。我试图重现您的问题,我想我找到了您问题的症结所在。您必须将名称设置器从
if (name != null)
{
name = value;
RaisePropertyChanged("Name");
}
到
因此,原因是
DisplayMemberPath=“Name”
看起来不起作用,因为Name
毕竟是空的。感谢它起作用,您还知道如何将文本框添加到组合框吗?
if (name == null)
{
name = value;
RaisePropertyChanged("Name");
}