WPF Combobox có:
SelectedValuePath
tài sản đó quy định cụ thể đường dẫn đến tài sản đó được sử dụng để xác định giá trị của SelectedValue
tài sản. Nó tương tự như thuộc tính Value
của ASP.NET ListItem
.
DisplayMemberPath
thuộc tính xác định mẫu mặc định mô tả cách hiển thị đối tượng dữ liệu. Nó tương tự như tài sản Text
của ASP.NET ListItem
.
Hãy nói rằng bạn muốn bạn Combobox
để hiển thị một bộ sưu tập của KeyValuePair
đối tượng sau:
private static readonly KeyValuePair<int, string>[] tripLengthList = {
new KeyValuePair<int, string>(0, "0"),
new KeyValuePair<int, string>(30, "30"),
new KeyValuePair<int, string>(50, "50"),
new KeyValuePair<int, string>(100, "100"),
};
Bạn xác định một tài sản trong mô hình quan điểm của bạn trở về bộ sưu tập mà:
public KeyValuePair<int, string>[] TripLengthList
{
get
{
return tripLengthList;
}
}
Sau đó, XAML của bạn cho số Combobox
sẽ là:
<ComboBox
SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}"
ItemsSource="{Binding TripLengthList, Mode=OneTime}"
SelectedValuePath="Key"
DisplayMemberPath="Value" />
Nơi bạn đặt SelectedValuePath
và DisplayMemberPath
thuộc tính vào tên thuộc tính mong muốn của các đối tượng (Key
và Value
tương ứng) hiển thị theo số Combobox
.
Hoặc, nếu bạn thực sự muốn thêm các mục vào Combobox
ở mã phía sau thay vì sử dụng một ràng buộc, bạn cũng có thể làm điều đó.Ví dụ:
<!--XAML-->
<ComboBox x:Name="ComboBoxFrom"
SelectedValue="{Binding FilterService.TripLengthFrom, Mode=TwoWay}" />
// Code behind
public partial class FilterView : UserControl
{
public FilterView()
{
this.InitializeComponent();
this.ComboBoxFrom.SelectedValuePath = "Key";
this.ComboBoxFrom.DisplayMemberPath = "Value";
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(0, "0"));
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(30, "30"));
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(50, "50"));
this.ComboBoxFrom.Items.Add(new KeyValuePair<int, string>(100, "100"));
}
ví dụ: một số giá trị int –