【问题标题】:MVVM SelectedValue from ComboBox returns NullComboBox 中的 MVVM SelectedValue 返回 Null
【发布时间】: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


【解决方案1】:

所以简单的答案(我想,我还没有测试过)是你的ComboBox 上没有设置SelectedValuePath(正如 vesan 在 cmets 中所述)。 这意味着SelectedValue 将永远是null

您可以使用SelectedItem 返回选定的Car,然后从中获取属性,或者只是在ComboBox 上设置SelectedValuePath

现在,这当然可以通过使用绑定来做得更好,但这取决于你是否要实现它。

【讨论】:

    猜你喜欢
    • 2021-07-07
    • 2013-12-01
    • 2011-04-21
    • 2021-09-14
    • 1970-01-01
    • 2010-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多