2016-04-17 85 views
0

問題があります。私はstringブランドの車クラスを持っています、stringモデル、.. 私はまた、データを含むComboBoxのビューを持っています。 ComboBox「carBrand」またはComboBox「carModel」の項目を選択してボタンをクリックすると、新しい車のオブジェクトを作成します。しかし、ボタンをクリックした後、から項目を選択したにもかかわらず、carBrand.SelectedValue.ToString()Nullの値をcarModelと同じ値で返します。私は誰かがこの問題を修正する私を助けることができると思います
ComboBoxのMVVM SelectedValueがNULLを返します

<!--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> 

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 
    //... 
} 

今私のビュークラス:私のVMClassで

ありがとうございます!

+0

comboboxのselecteditemに適切なアイテムをバインドしようとします – sexta13

+0

あなたの 'carBrand.SelectedValue'はヌルですか?私はあなたのXAMLでこの要素を見ることができません。理想的には、 'SelectedValue'をビューモデルのプロパティにバインドして(ここで' ItemsSource'をバインドしている場所)、そこから取得するのが理想的です。 – vesan

答えて

0

(私はまだテストしていないと思いますが)ComboBoxにはSelectedValuePathが設定されていないということです(このコメントのvesanに記載されています)。 これは、SelectedValueが常にnullになることを意味します。

選択したCarを返した後、そこからプロパティを取得またはちょうどComboBoxSelectedValuePathを設定するためにSelectedItemを使用することができます。

これはもちろん、バインディングを使用することでさらに改善することができますが、これを実装するかどうかはあなた次第です。

関連する問題