【问题标题】:SelectedItem and SelectedValue returns the wrong itemSelectedItem 和 SelectedValue 返回错误的项目
【发布时间】:2014-12-30 19:30:52
【问题描述】:

我有 List<string> MyList 有 4 个值。这些显示在ComboBox 控件中。该绑定在我的 MVVM WPF 项目中完美运行。

我还有一个string SelectedMyList,它绑定到我的 XAML 并且应该显示所选项目。我遇到的问题是,无论使用SelectedItem SelectedValue,它总是通过MyList中的第一项

private MyClass()//constructor
{
    MyList = new List<string>() {"Hi", "Bye", "Hello", "See ya"}; 
}

private string _selectedMyList;
public string SelectedMyList
{
    get
    {
        return this._selectedMyList;
    }
    set
    {
        //value is always Hi
        if (this._selectedMyList== value)
            return;

        this._selectedMyList= value;
        OnPropertyChanged("SelectedMyList");
    }
}

private List<string> _myList;
public List<string> MyList
{
    get
    {
        return this._myList;
    }
    set
    {
        if (this._myList== value)
            return;

        this._myList= value;
        OnPropertyChanged("MyList");
    }
}

还有我的 XAML

<ComboBox ItemsSource="{Binding MyList}" SelectedValue="{Binding SelectedMyList, UpdateSourceTrigger=PropertyChanged}" />

输出窗口中没有错误/绑定错误等。

为什么 SelectedItem/SelectedValue 不传递我认为是来自 ComboBox 的选定项?

【问题讨论】:

  • 您是否在 xaml 或代码后面设置了 DataContext
  • @YuliamChandra,如果我没有设置 DataContext,那么 MyList 将如何绑定?

标签: c# wpf xaml mvvm


【解决方案1】:

这对我有用。

  private string _selectedMyList;
    public string SelectedMyList
    {
        get
        {
            return this._selectedMyList;
        }
        set
        {
            //value is always Hi
            if (this._selectedMyList != value)
            {
                this._selectedMyList= value;
                OnPropertyChanged("SelectedMyList");
            }
        }
    }

    private List<ObservableCollection> _myList;
    public ObservableCollection<string> MyList
    {
        get
        {
            return this._myList;
        }
        set
        {
            if (this._myList== value)
            {
                this._myList= value;
                OnPropertyChanged("MyList");
            }
        }
    }

Xaml:

<ComboBox ItemsSource="{Binding MyList}" 
          SelectedItem="{Binding SelectedMyList}" 
          IsSynchronizedWithCurrentItem="True"/>

【讨论】:

  • 不知道为什么我需要同步它......我怀疑还有其他事情发生,但这确实解决了它。谢谢
【解决方案2】:

如果要使用 SelectedValue 属性,则需要将其与 SelectedValuePath 属性一起使用。 See this link to a similar question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 1970-01-01
    相关资源
    最近更新 更多