当SelectedItem的绑定值发生更改时,ComboBox不会更改

时间:2011-08-23 20:09:54

标签: silverlight data-binding combobox

我有一个ComboBox,其ItemSourceSelectedItem属性绑定到视图模型。我有以下代码块,它是针对DomainContext的数据查询的回调:

    /// <summary>
    /// Stores (readonly) - Stores available for ship to store.
    /// </summary>
    public ObservableCollection<StoreEntity> Stores
    {
        get { return _stores; }
        private set { _stores = value; RaisePropertyChanged("Stores"); }
    }

    /// <summary>
    /// SelectedStore - Currently selected store.
    /// </summary>
    public StoreEntity SelectedStore
    {
        get { return _selectedStore; }
        set { _selectedStore = value; RaisePropertyChanged("SelectedStore"); }
    }

    /// <summary>
    /// When stores are completely loaded.
    /// </summary>
    /// <param name="a_loadOperations"></param>
    protected void OnStoresLoaded(LoadOperation<StoreEntity> a_loadOperations)
    {
        Stores.AddRange(a_loadOperations.Entities);
        SelectedStore = a_loadOperations.Entities.FirstOrDefault();
    }

在此示例中,StoresObservableCollection<StoreEntity>AddRange是一种扩展方法)并且绑定到ItemSource,而SelectedStoreStoreEntity 1}}并且绑定到SelectedItem

此处的问题是,ComboBox并未更改其选择以反映SelectedItem中的更改。

编辑:

我甚至尝试了以下内容,但我认为a_loadOperation.Entities已经是一个已实现的集合:

    /// <summary>
    /// When stores are completely loaded.
    /// </summary>
    /// <param name="a_loadOperations"></param>
    protected void OnStoresLoaded(LoadOperation<StoreEntity> a_loadOperations)
    {
        var entities = a_loadOperations.Entities.ToArray();
        Stores.AddRange(entities);
        SelectedStore = entities.First();
    }

由于

2 个答案:

答案 0 :(得分:1)

如果您尝试更改要在组合框中反映的viewmodel(特别是SelectedStore属性),您可以:

  1. 确认绑定有效。检查它是否已在XAML中正确设置,并检查“输出”窗口以查看是否有消息说“绑定失败”
  2. 确认您的DataContext已正确设置(可能是因为您从“商店”获取组合框`ItemsSource`
  3. 订阅PropertyChanged事件并确认在属性更改时引发该事件
  4. 如果这不起作用,则可能是ComboBox的错误。我见过在XAML中指定属性的顺序有所区别的情况(例如:你应该先设置ItemsSource,然后选择SelectedItem)。我还看到绑定失败,直到我添加Mode = TwoWay(即使在您的示例中,您尝试从视图模型更新绑定到您的UI)。尝试确认您的ComboBox XAML是这样的: <ComboBox ItemsSource="{Binding Stores}" SelectedItem="{Binding SelectedStore, Mode=TwoWay}" /> 顺序无关紧要,因为XAML是声明性的,但我个人认为它与Silverlight中的ComboBox有关。

答案 1 :(得分:0)

SelectedItem绑定了Stores而不是SelectedStore。哎呀!

相关问题