gpt4 book ai didi

c# - MVVM 将一个 ComboBox 与另一个绑定(bind)

转载 作者:行者123 更新时间:2023-12-03 10:27:07 24 4
gpt4 key购买 nike

我对 MVVM 很陌生,我想问一下,您是否可以帮助我将 SelectedValue 从 ComboBox 获取到我的 VM-Class。在我的示例中,我有一个包含所有汽车品牌的 ComboBox。如果我选择一个汽车品牌,我希望在另一个 ComboBox 中拥有该汽车品牌的所有型号以供选择。我已经进行了一些研究,但我找不到解决问题的单一方法。

After clicking on the Brand-ComboBox.

到目前为止这很好,但是当我想要显示模型时,ComboBox 保持为空。

来自我的 的代码查看级 :`

<ObjectDataProvider x:Key="vmcars" ObjectType="{x:Type local:VMCars}"/>

<!--MainGrid-->
<Grid DataContext="{StaticResource vmcars}">
.
.
.
.
</Grid>

来自我的 的代码品牌-ComboBox :
        <!--CarBrand Combobox-->
<ComboBox x:Name="carBrand" Style="{StaticResource combobox}"
ItemsSource="{Binding AllCars}"
Grid.Column="1" Grid.Row="1"
DisplayMemberPath="c_brand"
Margin="20,13,17,15"
VerticalAlignment="Center" Height="30">
<ComboBox.SelectedItem>
<Binding Path="SelectedBrand"
BindsDirectlyToSource="True"
Mode="OneWayToSource" />
</ComboBox.SelectedItem>
</ComboBox>

来自我的 的代码型号-ComboBox :
        <!--CarModel ComboBox-->
<ComboBox x:Name="carModel" Style="{StaticResource combobox}" Grid.Column="1"
Margin="20,15,17,14"
ItemsSource="{Binding ModelSelectedBrand}" DisplayMemberPath="c_model"
Grid.Row="2" VerticalAlignment="Center" Height="30">
</ComboBox>

来自我的 的代码虚拟机类 :
    public string selectedBrand;
public string SelectedBrand
{
get { return selectedBrand; }
set
{
selectedBrand = value;
PropertyChanged(this, new PropertyChangedEventArgs
("ModelSelectedBrand"));

}
}

public IEnumerable<c_car> ModelSelectedBrand
{
get
{
return (from c in db.c_car
where c.c_brand.Equals(SelectedBrand) //THIS IS CAUSING PROBLEMS

select c).GroupBy(x=>x.c_model).Select(x=>x.FirstOrDefault()).OrderBy(x=>x.c_model).ToList();
}
}

然后当我评论 地点 我的 Linq 语句中的子句,我得到了这个结果:
click here

这些是 全部 汽车模型。

我认为问题在于我的“ SelectedBrand ”属性没有从 中获得任何值。汽车品牌组合框

因此,我想问您,是否有人知道可能导致麻烦的原因。

最佳答案

您的汽车品牌ComboBox当前正在传递 c.car 的类名到您的查询。如果您绑定(bind)到 SelectedValue而不是 SelectedItem , 并设置 SelectedValuePath"c_car"有用。

因此,您的新 CarBrand ComboBox 定义将是

<!--CarBrand Combobox-->
<ComboBox x:Name="carBrand" Style="{StaticResource combobox}"
ItemsSource="{Binding AllCars}"
Grid.Column="1" Grid.Row="1"
DisplayMemberPath="c_brand"
SelectedValuePath="c_brand"
Margin="20,13,17,15"
VerticalAlignment="Center" Height="30">
<ComboBox.SelectedValue>
<Binding Path="SelectedBrand"
BindsDirectlyToSource="True"
Mode="OneWayToSource" />
</ComboBox.SelectedValue>
</ComboBox>

关于c# - MVVM 将一个 ComboBox 与另一个绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com