如何从列表中获取所选值wpf c#?

时间:2016-11-01 18:32:35

标签: c# wpf data-binding combobox

我需要在组合框中显示值,还需要从组合框中保存选定的值。 为了在组合框中显示值,我有列表。我可以在组合框中显示值。我需要帮助才能从组合框中获取所选值以便保存

_TheList.Add("Accecpted");
_TheList.Add("Not Accecpted");

public List<string> _TheList = new List<string>();
    public List<string> TheList
{
    get
    {                
        return _TheList;
    }
    set
    {
        _TheList = value;
        OnPropertyChanged("TheList");

    }
}
public void OnPropertyChanged(string propertyName)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

public event PropertyChangedEventHandler PropertyChanged;

XAML:

        <DataTemplate>
            <ComboBox                                      
               ItemsSource="{Binding TheList}"
               SelectedIndex="0"        
               IsSynchronizedWithCurrentItem="True"
              />
        </DataTemplate>

1 个答案:

答案 0 :(得分:1)

在您的c#代码中,添加以下属性

string _selectedItem;
public string SelectedItem
{
    get
    {
        return _selectedItem;
    }
    set
    {
        _selectedItem = value;
        PropertyChanged("SelectedItem");
    }
}
你的xaml

中的

<ComboBox                                      
    ItemsSource="{Binding TheList}"
    SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
    SelectedIndex="0"        
    IsSynchronizedWithCurrentItem="True"
/>