【发布时间】:2014-01-02 22:42:13
【问题描述】:
我遇到了一个 ComboBox 在加载弹出控件时不显示 SelectedItem 的问题。我正在使用 MVVM,所以除了初始化之外没有任何代码。我对编程很陌生,所以我希望我错过了一些简单的东西。但是,我有其他 ComboBoxes 可以在与这些相同的设置下正常工作,所以我很困惑。我想知道 Popup 控件是否有不同之处,或者我需要考虑使用多个视图模型。
我的 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}" />
这是我的视图模型中带有绑定属性的代码。
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;
}
这些属性可以很好地绑定到文本框,但不能绑定到 ComboBox。我真的对此感到困惑。非常感谢大家的帮助。
【问题讨论】:
-
您是否检查了输出窗口中的任何绑定错误?
-
感谢您的建议。我检查了输出窗口,没有绑定错误。