gpt4 book ai didi

c# - 将多个控件绑定(bind)到组合框中选定的对象

转载 作者:行者123 更新时间:2023-11-30 15:34:39 24 4
gpt4 key购买 nike

我有一个学生类(class),如下所示

public class Student
{
public string Name { get; set; }
public string Operator { get; set; }
public IList<Subject> Subjects { get; set; }
}

现在我要将这个学生的集合绑定(bind)到我的窗口的三个控件如下图

<ComboBox  Margin="12,28,0,0"
Name="cbStudents"
VerticalAlignment="Top"
ItemsSource="{Binding Path=PersonList}"
DisplayMemberPath="Name"
SelectedValuePath="Operator" />
<TextBox Margin="12,75,0,0"
Name="tbOperator"
VerticalAlignment="Top"
Text="{Binding ElementName=cbStudents,Path=SelectedValue}" />
<ComboBox Margin="12,123,0,0"
Name="cbSubjects"
VerticalAlignment="Top"
ItemsSource="{Binding ElementName=cbStudents, Path=SelectedValue}"
DisplayMemberPath="SubjectName" />

现在我担心的是,每当我更改 cbStudentst 中的选择时,在这种情况下,其他控件也应该更改其相应的值。根据上面给出的代码,每当 cbStudentschanges 中的选择 tbOperator 中的文本发生变化时,我也想为 cbSubjects 实现相同的代码。除了 cbStudents 的 SelectionChanged 事件之外,还有其他解决方法吗?

最佳答案

您希望 TextBox tbOperator 显示 ComboBox cbStudents 的 SelectedItem 的 Operator 并且另一个 ComboBox 包含 ComboBox cbStudents 的 SelectedItem 的主题

那么下面的 XAML 应该会做你想做的事(删除不相关的代码来解决你的问题):

<ComboBox Name="cbStudents" 
ItemsSource="{Binding Path=PersonList}"
DisplayMemberPath="Name" />
<TextBox Name="tbOperator"
Text="{Binding SelectedItem.Operator, ElementName=cbStudents}" />
<ComboBox Name="cbSubjects"
ItemsSource="{Binding SelectedItem.Subjects, ElementName=cbStudents}"
DisplayMemberPath="SubjectName" />

关于c# - 将多个控件绑定(bind)到组合框中选定的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15964281/

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