WPF组合框数据绑定所选项目
问题描述:
我想一个数据绑定组合框
到字符串列表
。到目前为止,我有以下几点:
I am trying to databind a ComboBox
to a list of strings
. So far I have got the following:
在我查看我有:
<ComboBox Height="23"
HorizontalAlignment="Left"
Margin="133,180,0,0"
Name="comboBox1"
ItemsSource="{Binding Hours}"
VerticalAlignment="Top"
Width="38" />
在我的ViewModel我有:
And in my ViewModel I have:
private List<string> tripTimeHours = new List<string>();
private List<string> tripTimeMinutes = new List<string>();
public CreateTripViewModel()
{
TripName = new DataWrapper<string>(this, tripNameChangeArgs);
TripName.IsEditable = true;
setObjects();
CreateTripFiredCommand = new SimpleCommand<object, EventToCommandArgs>(ExecuteCreateTripCommand);
}
private void setObjects()
{
for (int i = 0; i < 24; i++)
{
tripTimeHours.Add(i.ToString());
}
for (int i = 0; i < 60; i++)
{
tripTimeMinutes.Add(i.ToString());
}
}
public List<string> Hours
{
get
{
return tripTimeHours;
}
}
public List<string> Minutes
{
get
{
return tripTimeMinutes;
}
}
我希望能够做的是返回从这些组合框中选择的项目。我想,我几乎没有,只是需要完成的最后一步。
What I want to be able to do is return the selected item from these combo boxes. I think I'm almost there, but just need to complete the final step.
答
添加绑定到 ComboBox.SelectedItem
这势必一个新的字符串
属性上的视图模型
Add a binding to ComboBox.SelectedItem
which is bound to a new string
property on your ViewModel
<ComboBox ITemsSource="{Binding Hours}" SelectedItem="{Binding SelectedItem}" />
class ViewModel
{
public string SelectedItem {get; set;}
}