用数据库中的数据填充列表框.数据库中的值取决于组合框项目C#WPF MVVM的选择



从组合框中选择值后,应将值从数据库添加到列表框中。在我的情况下,我从组合框中选择一个学校班级。然后列表框应该显示这个班级的学生(从组合框中选择的学校班级(。学校的班级也来自数据库。组合框中充满了学校的类,我使用构造函数中调用的方法来填充它。学生应该在我点击一个按钮后显示出来。此单击是在绑定到按钮的命令属性的命令中完成的。逻辑在ViewModel类中,而不在Window.xaml.cs中,因为我在这里使用MVVM。列表框中没有来自数据库的数据,这就是问题所在。未显示任何内容

以下是我的ViewModel代码:

命令属性:

public ICommand SearchCommand
{
get
{
if (searchCommand == null)
{
searchCommand = new RelayCommand(() => searchStudents());
}
return searchCommand;
}
}

方法:

public void searchStudents()
{
try
{
mySqlConnection.Open();
string query = "SELECT * FROM `studentmanagement-db`.tbl_student WHERE FK_Klasse= @FK_Klasse;";
MySqlCommand command = new MySqlCommand(query, mySqlConnection);
command.Parameters.AddWithValue("@FK_Klasse", KlasseProp.KlassenIDFK);
command.ExecuteNonQuery();
MySqlDataAdapter sqlDataAdapter = new MySqlDataAdapter(command);
using (sqlDataAdapter)
{
DataTable studentTable = new DataTable();
sqlDataAdapter.Fill(studentTable);
var result = studentTable;
SchuelerProp.Vorname = "Vorname"; 
SchuelerProp.ItemSource = studentTable.DefaultView;
SchuelerProp.SchuelerID = "tbl_student_id";
}
}
catch (Exception e)
{
MessageBox.Show(e.StackTrace);
}
finally
{
mySqlConnection.Close();
}

以下是来自xaml:的绑定

<ComboBox x:Name="Combo_Klassen" HorizontalAlignment="Center" VerticalAlignment="Top" Margin="20,10,10,10" Width="100" Height="25"
ItemsSource="{Binding Path=KlasseProp.ItemSource, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
DisplayMemberPath="{Binding Path=KlasseProp.KlassenNamen}"
SelectedValue="{Binding KlasseProp.KlassenIDFK}"
SelectedValuePath="{Binding Path=KlasseProp.KlassenID}"
>
</ComboBox>
<Button x:Name="Button_Search" Content="search" VerticalAlignment="Top" HorizontalAlignment="Right" Width="50" Height="25" Margin="20,10,50,10" VerticalContentAlignment="Center"
Command="{Binding Path=SearchCommand}"/>
<ListBox x:Name="Listbox_Students" Margin="50,100,50,75"
ItemsSource="{Binding Path=SchuelerProp.ItemSource, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"
DisplayMemberPath="{Binding Path=SchuelerProp.Vorname}"
SelectedValuePath="{Binding Path=SchuelerProp.SchuelerID}"
SelectedValue="{Binding Path=SchuelerProp.Schueler_ID}"
>
</ListBox>

尝试将SelectedValueUppdateSourceTrigger设置为OnPropertyChanged,如下所示:SelectedValue="{Binding Path=KlasseProp.KlassenIDFK, UpdateSourceTrigger=PropertyChanged}"

最新更新