我遇到了一个 ComboBox 在加载弹出控件时不显示 SelectedItem 的问题。我正在使用 MVVM,所以除了初始化之外没有任何代码。我对编程很陌生,所以我希望我错过了一些简单的东西。但是,我有其他 ComboBoxes 可以在与这些相同的设置下正常工作,所以我很困惑。我想知道 Popup 控件是否有不同之处,或者我需要考虑使用多个 View 模型。
我的 Popup 用户控件内的 ComboBox 的标记代码如下:
<ComboBox Name="comboBox1"
Height="23"
Margin="5,280,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
IsEnabled="{Binding PaymentScheduleBaseUnitEnabled}"
ItemsSource="{Binding Path=ScheduleBaseUnitList,
Mode=OneWay}"
SelectedItem="{Binding Path=SelectedBaseUnitPaymentFrequencyChoice,
Mode=TwoWay}"
Style="{StaticResource ComboBoxShort}" />
这是我的 View 模型中带有绑定(bind)属性的代码。
public ObservableCollection<ScheduleBaseUnit> ScheduleBaseUnitList
{
get
{
_scheduleBaseUnitList = _utilityRepository.GetScheduleBaseUnitList();
return _scheduleBaseUnitList;
}
set
{
_scheduleBaseUnitList = value;
OnPropertyChanged("ScheduleBaseUnitList");
}
}
和 SelectedBaseUnitPaymentFrequencyChoice 属性。
public ScheduleBaseUnit SelectedBaseUnitPaymentFrequencyChoice
{
get
{
if (_selectedBaseUnitPaymentFrequencyChoice != null)
{
return
_scheduleBaseUnitList.FirstOrDefault(
c => c.ScheduleBaseUnitId == _selectedBaseUnitPaymentFrequencyChoice.ScheduleBaseUnitId);
}
}
set
{
if (_paymentFrequencyCustomer != null)
{
_paymentFrequencyCustomer.ScheduleBaseUnit = value;
OnPropertyChanged("SelectedBaseUnitPaymentFrequencyChoice");
OnPropertyChanged("TestTwo");
}
}
}
这是 ScheduleBaseUnit 类
public class ScheduleBaseUnit : INotifyPropertyChanged
{
public int ScheduleBaseUnitId { get; set; }
public string Description { get; set; }
public ScheduleBaseUnit(int ScheduleBaseUnitId, string Description)
{
this.ScheduleBaseUnitId = ScheduleBaseUnitId;
this.Description = Description;
}
public ScheduleBaseUnit()
{
}
public override string ToString()
{
return this.Description;
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public bool Equals(ScheduleBaseUnit sbUnit)
{
if (sbUnit == null)
return false;
//return true if the fields match
return sbUnit.ScheduleBaseUnitId == this.ScheduleBaseUnitId;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public event PropertyChangedEventHandler PropertyChanged;
}
这些属性将很好地绑定(bind)到文本框,但不会绑定(bind)到 ComboBox。我真的对此感到困惑。非常感谢大家的帮助。
最佳答案
我的第一个想法是,您实际上并没有从 Equals 覆盖中调用强类型 Equals 方法:
public override bool Equals(object obj)
{
return this.Equals(obj as ScheduleBaseUnit);
}
作为最佳实践,您还应该向 GetHashCode 添加更有用的覆盖,例如:
public override int GetHashCode()
{
return this.ScheduleBaseUnitId.GetHashCode();
}
如果这些都不起作用,您确定所选项目在 ItemsSource 集合中吗?
关于c# - 使用 MVVM 将 WPF 绑定(bind)到 Popup 控件中的 ComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20893312/