我已经尝试了看起来一生只能让这个问题排序,但遗憾的是无济于事..甚至在搜索stackoverflow和其他网站之后 .
我会尽量避免我的问题,但要注意这一点 .
使用WPF和MVVM方法我有:View和ViewModel .
在视图XAML中,我将一个comboBox绑定到一个键/值字典对象中的值列表 . 这很好 - 当我点击组合框时,我能够看到值下拉 .
注意:每个记录在gridview中可以显示多个分期付款,其中显示组合框 .
<dxg:GridColumn Header="Instalments"
Width="100"
AllowSorting="False"
AllowAutoFilter="False">
<dxg:GridColumn.CellTemplate>
<DataTemplate>
<ComboBox IsEnabled="{Binding Data.IsIncludedInDD}"
Name="cbInstalmentValues"
Width="200"
ItemsSource="{Binding Data.D_InstalmentValues}"
SelectedIndex="{Binding Data.Instalments, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
DisplayMemberPath="Value"
SelectedValuePath="Key"
SelectedValue="{Binding SelectedInstalmentValue, Mode=TwoWay, ValidatesOnDataErrors=True, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"
VerticalAlignment="Center" />
码:
private static readonly Dictionary<int, string> D_instalmentValues = new Dictionary<int, string>
{
{0, "None"},
{1, "1 Instalment"},
{2, "2 Instalments"},
{3, "3 Instalments"},
{4, "4 Instalments"},
{5, "5 Instalments"},
{6, "6 Instalments"},
{7, "7 Instalments"},
{8, "8 Instalments"},
{9, "9 Instalments"},
{10, "10 Instalments"},
{11, "11 Instalments"},
{12, "12 Instalments"}
};
public Dictionary<int, string> D_InstalmentValues
{
get
{
return _instalmentValues;
}
set
{
_instalmentValues = value;
}
}
所以..当我加载我的应用程序时,我希望comboBox从viewmodel中的'Installments'属性中读取值并绑定到字典中值的相同索引并显示分期数...即:None, 1分期等
public int Instalments
{
get
{
return _chargeTemplate.Instalments;
}
set
{
if (value == -1)
{
value = value + 1;
_chargeTemplate.Instalments = _chargeTemplate.Instalments;
}
else
{
if (_chargeTemplate.Instalments == value)
{
return;
}
else
{
_chargeTemplate.Instalments = value;
}
}
//NotifyNotRegister("Instalments");
RaisePropertyChanged("Instalments");
}
}
现在'_chargeTemplate.Instalments'值保存数据库中记录的分期付款列中的值 .
如果Installments属性中的值为0,则组合框似乎不会绑定 . 该框为空 .
在选择值大于0的记录后,它会填充 .
当我尝试使用1到12的值填充sql表中的所有分期字段时,所选索引没有为我的应用程序中显示的第一条记录正确设置,但如果我选择了下一条记录则显示确定...则如果我再次重新选择第一条记录,它也会正确显示 .
行为的另一个奇怪的部分是第一个记录,如果我有3个分期付款,并且在sql表中分期付款1 = 2,分期付款2 = 4和分期付款3 = 0 ...该记录的前两部分有他们的组合框索引设置但最后一条记录为空 .
总而言之 - 我需要知道在应用程序加载时如何使所选索引从视图模型绑定到视图,而第一个记录的组合框不为空,或者所选索引为0的值 .
我希望这里有足够的信息......
非常感谢
更新:
我对XAML和我绑定组合框选择索引的属性进行了一些小改动 . 这允许0值在组合框中显示“无”,其中值为0表示sql数据库中的人员分期值 .
但是,记录列表中显示的第一个人没有将选择的索引设置为字典值的索引,除非我选择另一个人并再次重新选择第一个人...奇怪
视图模型
public int Installments {get {return _chargeTemplate.Instalments; }}
XAML
SelectedIndex =“{Binding Data.Instalments,Mode = OneWay}”
1 回答
我终于在盯着屏幕看了一眼之后找到了答案,并意识到我遗漏了1个字!
我完全从组合框控件中删除了“SelectedIndex”属性,而是使用了“SelectedValue” . 前面缺少的词是'数据' .
通过对viewmodel中的属性进行一些调整,这可以在加载应用程序时从数据库中显示组合框中的正确值 .
见下文:)
谢谢!