gpt4 book ai didi

c# - 组合框绑定(bind) MVVM WPF SelectedValue

转载 作者:行者123 更新时间:2023-12-03 10:35:50 25 4
gpt4 key购买 nike

获取组合框的选定值时出现问题。我得到的错误是,我似乎无法修复它,尝试了绑定(bind)、selectedvaluepath 等的各种组合,希望有人能指出我正确的方向,谢谢!

ConvertBack cannot convert value 'ClientRatesWPF.Model.ChargeUnit' (type 'ChargeUnit'). BindingExpression:Path=SelectedChargeUnitListValueId; DataItem='ClientRatesViewModel' (HashCode=33434731); target element is 'ComboBox' (Name='cmbChargeUnit'); target property is 'SelectedValue' (type 'Object') NotSupportedException:'System.NotSupportedException: Int32Converter cannot convert from 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"/>

虚拟机:
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 集合(从方法中提取的代码)
while (reader.Read())
{
_chargeUnitsCollection.Add(new ChargeUnit
{
ChargeUnitListValueId = (int)reader["ListValueId"],
ChargeUnitDescription = reader["ValueName"].ToString()
});
}

最佳答案

所以你有一个组合框,其中包含 ChargeUnit 的列表的,您正在尝试设置 SelectedValueint那将是你的问题。需要改成选中的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");
}
}

并在您的绑定(bind)中:
SelectedValue="{Binding SelectedChargeUnit}"

关于c# - 组合框绑定(bind) MVVM WPF SelectedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29984658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com