【问题标题】:WPF ComboBox SelectedItem Binding Doesn't WorkWPF ComboBox SelectedItem 绑定不起作用
【发布时间】:2011-05-05 10:11:59
【问题描述】:

我有以下从枚举中获取的组合框:

<ComboBox Name="cmbProductStatus" ItemsSource="{Binding Source={StaticResource statuses}}" 
                                                  SelectedItem="{Binding Path=Status}" />

请注意,DataContext 是在代码隐藏中设置的。

这甚至不是双向绑定,我有一些 Product.Status 的默认值,但它永远不会被选中。

更新

我被要求输入我的 Status 属性的代码。

public class Product    {
    //some other propertties
    private ProductStatus _status = ProductStatus.NotYetShipped;
    public ProductStatus Status { get { return _status; } set { value = _status; } }
}

public enum ProductStatus { NotYetShipped, Shipped };

【问题讨论】:

  • 在调试器下运行时查看您的输出窗口,看看它是否告诉您有关绑定到状态的任何信息。
  • 您能提供您的 Status 属性的代码吗?如果它无法绑定,我会在输出窗口中期待一些东西。
  • 如果您想看到更改显示在您的 GUI 中,您需要实现 INotifyPropertyChanged 并以“状态”作为值引发正确的事件。只要您的 ItemSource 包含枚举,尽管我原以为您会获得默认设置。我的博客上有一些关于绑定的调试技巧,您可能会觉得有用。如果您有兴趣,请点击我的名字 - 那里有一个链接。
  • @Russell 感谢您提供调试提示。我的 DataItem 似乎为空。我认为这是因为 ItemSource 设置为 StaticResource,而父容器的 DataContext 设置在代码隐藏中。

标签: c# .net wpf binding


【解决方案1】:

ComboBox 绑定有点棘手。确保在分配 DataContext 时加载 itemssource,并且使用 SelectedItem 分配的项目满足与 ItemsSource 中一项的 == 关系。

【讨论】:

  • 感谢您的回答。 ItemSource 已加载,它只是一个静态枚举。
  • 对于在模型类上实现 .Equals(object) 的非枚举类型就可以了。
【解决方案2】:

您的 status 属性必须通知其更改,并且您的 Product 类必须实现 INotifyPropertyChanged 接口。

这里有属性的 MVVM Light 代码 sn-p ;-)

/// <summary>
        /// The <see cref="MyProperty" /> property's name.
        /// </summary>
        public const string MyPropertyPropertyName = "MyProperty";

        private bool _myProperty = false;

        /// <summary>
        /// Gets the MyProperty property.
        /// TODO Update documentation:
        /// Changes to that property's value raise the PropertyChanged event. 
        /// This property's value is broadcasted by the Messenger's default instance when it changes.
        /// </summary>
        public bool MyProperty
        {
            get
            {
                return _myProperty;
            }

            set
            {
                if (_myProperty == value)
                {
                    return;
                }

                var oldValue = _myProperty;
                _myProperty = value;

                // Remove one of the two calls below
                throw new NotImplementedException();

                // Update bindings, no broadcast
                RaisePropertyChanged(MyPropertyPropertyName);

                // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
                RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
            }
        }

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 2015-06-28
    • 2010-10-24
    • 1970-01-01
    • 2017-11-09
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多