I have a problem. I have a car class with string
brand, string
model,.. I also have a view with a ComboBox
containing Data. When I select an item from the ComboBox
"carBrand" or the ComboBox
"carModel" and click on a button, I want to create a new car object. But after clicking on the button, the carBrand.SelectedValue.ToString()
is delivering a Null
value, same for carModel, although I selected an item from the ComboBox
.
In my 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
//...
}
Now my 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>
I hope someone can help me fixing this issue.
Thanks in advance!
So the simple answer (I think, I haven't tested yet) is that there isn't a SelectedValuePath
set on your ComboBox
(As stated by vesan in the comments). This means that SelectedValue
will always be null
.
You could use SelectedItem
to return the selected Car
and then get the property from that or just set the SelectedValuePath
on the ComboBox
.
Now, this could of course be made better by using bindings but that is up to you whether you want to implement this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.