【问题标题】:ComboBox not changing when bound value of SelectedItem changes当 SelectedItem 的绑定值更改时,ComboBox 不会更改
【发布时间】:2011-08-23 20:09:54
【问题描述】:

我有一个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&lt;StoreEntity&gt;AddRange 是一种扩展方法)并绑定到 ItemSourceSelectedStoreStoreEntity 并绑定到 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();
    }

谢谢

【问题讨论】:

  • 看来一切都设置正确了。你能告诉我们你设置绑定的 xaml 部分吗?
  • 你是不是把绑定模式设置为双向
  • 在我们的解释中,您将其称为 SelectedItem,但该属性称为 SelectedStore - 仔细检查您的 xaml 以查看是否存在这种情况。
  • 啊!我发现了我的问题。我将SelectedItem 绑定到Stores
  • @EtherDragon,SelectedItemComboBox 上的属性,SelectedStore 是绑定到 SelectedItem 的视图模型中的属性。

标签: silverlight data-binding combobox


【解决方案1】:

如果您试图更改您的视图模型(特别是 SelectedStore 属性)以反映在您的组合框中,您可以:

  1. 确认绑定工作。检查它是否在 XAML 中正确设置,并检查输出窗口以查看是否有消息说绑定失败
  2. 确认您的 DataContext 设置正确(可能是因为您从 `Stores` 获取组合框 `ItemsSource`
  3. 订阅您的 PropertyChanged 事件并确认在属性更改时引发该事件

如果这不起作用,则可能是 ComboBox 的错误。我已经看到在 XAML 中指定属性的顺序会有所不同的情况(例如:您应该首先设置 ItemsSource,然后设置 SelectedItem)。在添加 Mode=TwoWay 之前,我还看到绑定失败(即使在您的示例中,您正试图让绑定从您的视图模型更新到您的 UI)。尝试确认您的 ComboBox XAML 是这样的: &lt;ComboBox ItemsSource="{Binding Stores}" SelectedItem="{Binding SelectedStore, Mode=TwoWay}" /&gt; 由于 XAML 是声明性的,因此顺序应该无关紧要,但我个人认为 Silverlight 中的 ComboBox 很重要。

【讨论】:

  • 正如我在您写答案之前所说的那样,我自己解决了这个问题。请参阅有问题的帖子。谢谢。
  • 我看到你 4 小时前的评论说你发现了问题。但是,我在 16 小时前写了我的回复。无论如何,很高兴你明白了。绑定可能特别棘手,因为您没有得到太多关于它们为什么不起作用的反馈。
  • 哦,对不起。直到后来才看到。
【解决方案2】:

我将SelectedItem 绑定到Stores 而不是SelectedStore。哎呀!

【讨论】:

    猜你喜欢
    • 2021-09-26
    • 2011-12-05
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多