【发布时间】:2016-08-09 09:14:36
【问题描述】:
我有问题。我有 string 品牌、string 型号的汽车课程,..
我也有一个包含数据的ComboBox 视图。当我从ComboBox“carBrand”或ComboBox“carModel”中选择一个项目并单击一个按钮时,我想创建一个新的汽车对象。但是在点击按钮后,carBrand.SelectedValue.ToString() 提供了一个Null 值,对于 carModel 也是如此,尽管我从ComboBox 中选择了一个项目。
在我的 VMClass 中:
Add a1 = new Add();
c_car m1 = param as c_car;
a1.DataContext = m1;
a1.ShowDialog();
if (a1.DialogResult.HasValue && a1.DialogResult.Value)
{
m1.c_brand = a1.carBrand.SelectedValue.ToString(); //causes NullReferenceException
m1.c_model = a1.carModel.SelectedValue.ToString(); //causes NullReferenceException
m1.c_year = a1.carYear.Content.ToString(); //this works perfectly
m1.c_km = Int32.Parse(a1.carKm.Content.ToString()); //this also works properly
//...
}
现在是我的View Class:
<!--CarModel ComboBox-->
<ComboBox x:Name="carModel" Style="{StaticResource combobox}" Grid.Column="1"
Margin="20,15,17,14"
ItemsSource="{Binding ModelSelectedBrand}" DisplayMemberPath="c_model" MouseLeave="carModel_MouseLeave"
Grid.Row="2" VerticalAlignment="Center" Height="30" MouseDoubleClick="carModel_MouseDoubleClick">
</ComboBox>
<!--CarYear EditableLabel-->
<Label x:Name="carYear" Content="{Binding ElementName=carModel, Path=SelectedValue.c_year}" Margin="20,14,17,14"
Style="{StaticResource EditableLabelStyle}" Foreground="White"
Grid.Column="1" Grid.Row="5" VerticalAlignment="Center" Height="30">
</Label>
<!--CarKM EditableLabel-->
<Label x:Name="carKm"
Content="{Binding ElementName=carModel, Path=SelectedItem.c_km}" Style="{StaticResource EditableLabelStyle}"
Margin="20,14,17,14"
Grid.Column="1" Grid.Row="3" Foreground="White" VerticalAlignment="Center" Height="30">
</Label>
我希望有人可以帮助我解决这个问题。
提前致谢!
【问题讨论】:
-
尝试将一个selecteditem属性绑定到combobox中的selecteditem
-
您的
carBrand.SelectedValue是否为空?我在您的 XAML 中看不到此元素。理想情况下,您应该将SelectedValue绑定到视图模型的属性(可能是您现在绑定ItemsSource的位置)并从那里检索它。
标签: c# wpf mvvm combobox selectedvalue