WPF组合框数据绑定所选项

fra*_*mps 4 c# data-binding wpf mvvm

我正在尝试将a数据绑定ComboBox到列表中strings.到目前为止,我有以下内容:

在我看来,我有:

<ComboBox Height="23" 
          HorizontalAlignment="Left" 
          Margin="133,180,0,0" 
          Name="comboBox1" 
          ItemsSource="{Binding Hours}" 
          VerticalAlignment="Top" 
          Width="38" />
Run Code Online (Sandbox Code Playgroud)

在我的ViewModel中,我有:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要做的是从这些组合框返回所选项目.我想我差不多了,但只需要完成最后一步.

Mar*_*een 14

添加绑定到ViewModel上ComboBox.SelectedItem的新string属性的绑定

<ComboBox ITemsSource="{Binding Hours}" SelectedItem="{Binding SelectedItem}" />

class ViewModel
{
    public string SelectedItem {get; set;}
}
Run Code Online (Sandbox Code Playgroud)