wpf - 组合框不使用 SelectedValue WPF 进行初始化

标签 wpf listview data-binding combobox

在使用当前选定项初始化组合框时出现问题。

ClinicList 返回 ObservableCollection<Clinic>

      <ComboBox ItemsSource="{Binding Source={StaticResource ClinicList}}"
 DisplayMemberPath="Name" SelectedItem="{Binding SelectedClinic, 
    UpdateSourceTrigger=PropertyChanged}"></ComboBox>

我的 ComboBox 在绑定(bind)到员工的 ListView 中。一名员工可以分配多个诊所。

public class Employee{ 
...
public ObservableCollection<ClinicView> EmployeeClinics { get; set; }
}

public class ClinicView:INotifyPropertyChanged {

        private Clinic selectedClinic;
        public Clinic SelectedClinic {
            get { return selectedClinic; }
            set {
                selectedClinic = value;
                OnPropertyChanged("SelectedClinic");
            }
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName) {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
public class Clinic{
   public int ClinicId{get;set;}
   public string Name {get;set;
}

组合框在首次加载时显示为空白,并且每个员工的诊所数量都是正确的。下拉组合框包含正确的诊所,当我选择一个时,它会替换空白组合框文本并正确更新员工。

我的问题是为什么 Combobox 最初没有填充正确的文本而是空白?

enter image description here

编辑: ClinicList 是通过 window.resources 中的 ODP 设置的

 public static ObservableCollection<Clinic> GetClinicList() {
//gets list of clinics from db with ID
}

 <ObjectDataProvider MethodName="GetClinicList"
                            ObjectType="{x:Type local:MappingGenerators}"
                            x:Key="ClinicList">
        </ObjectDataProvider>

最佳答案

发现这篇文章可以挽救生命。

https://rachel53461.wordpress.com/2011/08/20/comboboxs-selecteditem-not-displaying/

以下是关键段落:

The problem is simple: By default WPF compares SelectedItem to each item in the ItemsSource by reference, meaning that unless the SelectedItem points to the same item in memory as the ItemsSource item, it will decide that the item doesn’t exist in the ItemsSource and so no item gets selected.

To work around this, you can either use the ComboBox’s SelectedValue and SelectedValuePath to set the SelectedItem by Value instead of by Item

关于wpf - 组合框不使用 SelectedValue WPF 进行初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29736958/

相关文章:

c# - 在任何布局控件的子项上获取 CollectionChanged 事件?

python - (django)根据用户的兴趣显示帖子

c# - 这是我们可以强制 ObjectDataSource 的唯一方法吗?

c# - 在 WPF 中放大图像

WPF "hex grid"组件

WPF Ribbon 4.0 - 控件级别的尺寸定义

java - 使用 Fragment 类中的数据库填充 android ListView 时发生意外错误

android - 从位图中获取 URI?

c# - 如何绑定(bind)到文本框

android - 数据绑定(bind) - safeUnbox 警告