[英]MVVM ComboBox Binding and add to combobox
Hi i want to make an Binding MVVM ComboBox that i can add any name i want in the combobox from the program not source code.嗨,我想制作一个绑定 MVVM 组合框,我可以从程序而不是源代码中在组合框中添加我想要的任何名称。 I tried something but when i open the ComboBox now is showing me this.
我尝试了一些东西,但是当我打开 ComboBox 时,现在向我展示了这一点。
Here is the code from the program and i don t know what is wrong, for me it's looks just fine.这是程序中的代码,我不知道有什么问题,对我来说它看起来很好。
Model:模型:
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");
}
}
}
}
}
ViewModel:视图模型:
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; }
}
}
}
ComboBox:组合框:
<Grid>
<ComboBox ItemsSource="{Binding Persons}" SelectedItem="{Binding Path=SPersons}" HorizontalAlignment="Left" Margin="208,135,0,0" VerticalAlignment="Top" Width="314" Height="27">
</ComboBox>
</Grid>
Try to put DisplayMemberPath="Name"
inside ComboBox.尝试将
DisplayMemberPath="Name"
放在 ComboBox 中。 For now you provided objects as a source and application does not know what to show, so it displays type.现在您提供对象作为源,应用程序不知道要显示什么,所以它显示类型。
Well I tried to reproduce your problem and I guess I found what was the point of your problem.好吧,我试图重现您的问题,我想我找到了您的问题的重点。 You have to change setter of Name from
您必须将 Name 的 setter 更改为
if (name != null)
{
name = value;
RaisePropertyChanged("Name");
}
to到
if (name == null)
{
name = value;
RaisePropertyChanged("Name");
}
So the reason DisplayMemberPath = "Name"
looks like it's not working because the Name
was null after all.所以
DisplayMemberPath = "Name"
看起来不起作用的原因是因为Name
毕竟是空的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.