WPF 组合框绑定
本文关键字:绑定 组合 WPF | 更新日期: 2023-09-27 18:37:16
嗨,我正在尝试将列表<>绑定到组合框。
<ComboBox Margin="131,242,275,33" x:Name="customer" Width="194" Height="25"/>
public OfferEditPage()
{
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;
Cusco = cusmo.Customer.ToList<Customer>();
customer.ItemsSource = Cusco;
customer.DisplayMemberPath = "name";
customer.SelectedValuePath = "customerID";
customer.SelectedValue = "1";
}
我没有错误,但组合框总是空的。库斯科是我名单的财产。我不知道这段代码有什么问题。你可以帮我吗?
迎接
public class Customer
{
public int customerID { get; set; }
public string name { get; set; }
public string surname { get; set; }
public string telnr { get; set; }
public string email { get; set; }
public string adress { get; set; }
}
这是客户类,这是我的模型。
public class CustomerViewModel
{
private ObservableCollection<Customer> _customer;
public ObservableCollection<Customer> Customer
{
get { return _customer; }
set { _customer = value; }
}
public CustomerViewModel()
{
GetCustomerCollection();
}
private void GetCustomerCollection()
{
Customer = new ObservableCollection<Customer>(BusinessLayer.getCustomerDataSet());
}
}
这就是视图模型。
尝试使用实际的 Binding 对象设置 ItemsSource 属性
XAML 方法(推荐):
<ComboBox
ItemsSource="{Binding Customer}"
SelectedValue="{Binding someViewModelProperty}"
DisplayMemberPath="name"
SelectedValuePath="customerID"/>
编程方法:
Binding myBinding = new Binding("Name");
myBinding.Source = cusmo.Customer; // data source from your example
customer.DisplayMemberPath = "name";
customer.SelectedValuePath = "customerID";
customer.SetBinding(ComboBox.ItemsSourceProperty, myBinding);
此外,客户属性上的资源库应引发属性更改事件
public ObservableCollection<Customer> Customer
{
get { return _customer; }
set
{
_customer = value;
RaisePropertyChanged("Customer");
}
}
如果上述方法不起作用,请尝试将绑定部分从构造函数移动到 OnLoaded 重写方法。 当页面加载时,它可能会重置您的值。
作为对史蒂夫答案的扩展,
您需要设置表单的数据上下文。
目前你有这个:
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = this;
应该改成这样:
InitializeComponent();
cusmo = new CustomerViewModel();
DataContext = cusmo;
然后,正如 Steve 所指出的,您将需要视图模型上的另一个属性来存储所选项目。