在获得所选的Combobox值时遇到问题。我得到的错误是,我似乎无法解决它,尝试了各种绑定,选择值路径等组合,希望有人可以指出我正确的方向,谢谢!
ConvertBack无法转换值'ClientRatesWPF.Model.ChargeUnit' (输入'ChargeUnit')。 BindingExpression:路径= SelectedChargeUnitListValueId; DataItem ='ClientRatesViewModel'(HashCode = 33434731);目标元素是 'ComboBox'(Name ='cmbChargeUnit'); target属性是'SelectedValue' (类型'Object')NotSupportedException:'System.NotSupportedException: Int32Converter无法从ClientRatesWPF.Model.ChargeUnit转换。
<av:ComboBox x:Name="cmbChargeUnit" HorizontalAlignment="Left" Margin="548,15,0,0" Width="187" ItemsSource="{av:Binding ChargeUnits}" DisplayMemberPath="ChargeUnitDescription" SelectedValue="{Binding SelectedChargeUnitListValueId}" VerticalAlignment="Top" Background="{av:DynamicResource {x:Static av:SystemColors.ControlDarkDarkBrushKey}}" Height="20" IsSynchronizedWithCurrentItem="True"/>
VM:
public ObservableCollection<ChargeUnit> ChargeUnits
{
get { return _chargeUnitsCollection; }
set { _chargeUnitsCollection = value; }
}
public IList<ChargeUnit> ChargeUnitDescription
{
get { return _chargeUnitDescription; }
set
{
_chargeUnitDescription = value;
OnPropertyChanged("ChargeUnitDescription");
}
}
public IList<ChargeUnit> ChargeUnitListValueId
{
get { return _chargeUnitListValueId; }
set
{
_chargeUnitListValueId = value;
OnPropertyChanged("ChargeUnitListValueId");
}
}
public int SelectedChargeUnitListValueId
{
get { return _SelectedChargeUnitListValueId; }
set
{
_SelectedChargeUnitListValueId = value;
OnPropertyChanged("SelectedChargeUnitListValueId");
}
}
我填充Observable Collection的地方(从方法中提取的代码)
while (reader.Read())
{
_chargeUnitsCollection.Add(new ChargeUnit
{
ChargeUnitListValueId = (int)reader["ListValueId"],
ChargeUnitDescription = reader["ValueName"].ToString()
});
}
答案 0 :(得分:1)
所以你有一个填充了ChargeUnit
列表的组合框,并且你试图将SelectedValue
设置为int
,这将是你的问题。您需要更改为所选的ChargeUnit
public int SelectedChargeUnitListValueId
{
get { return _SelectedChargeUnitListValueId; }
set
{
_SelectedChargeUnitListValueId = value;
var unitsWhere = ChargeUnits.Where(x => x.id == _SelectedChargeUnitListValueId);
if (unitsWhere.Count() > 0)
{
SelectedChargeUnit = unitsWhere.First();
}
OnPropertyChanged("SelectedChargeUnitListValueId");
}
}
public ChargeUnit SelectedChargeUnit
{
get { return _SelectedChargeUnit; }
set
{
_SelectedChargeUnit = value;
OnPropertyChanged("SelectedChargeUnit");
}
}
并在你的装订中:
SelectedValue="{Binding SelectedChargeUnit}"