我有一个组合框,从中获取API的值。我想获取该组合框中所选项目的ID,因为我下一个视图中的数据会根据此处选择的值而更改。
我的组合框。
<ComboBox x:Name="cmbSubjects" HorizontalAlignment="Right" Background="#FFE5DBE8" Width="141" SelectedItem="Maths" Margin="0,217,957,247" ItemsSource="{Binding Source={StaticResource cvsSubjects}}" PlaceholderText="Select"/>
这就是我填充它的方式。
private async void getSubjects()
{
try
{
string subjects = baseAddress + "subjects";
var cont = await httpClient.GetStringAsync(new Uri(subjects));
subjectHelper data = JsonConvert.DeserializeObject<subjectHelper>(cont);
foreach (var item in data.result)
{
cmbSubjects.Items.Add(item.name);
}
}
catch (Exception ex)
{
MessageDialog messageDialog = new MessageDialog(ex.Message);
messageDialog.ShowAsync();
}
}
我的课程:
public class Subject
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public string description { get; set; }
public curriculum curriculam { get; set; }
}
class subjectHelper
{
public List<Subject> result { get; set; }
}
public class unit
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public string description { get; set; }
public string image { get; set; }
public int teachingHours { get; set; }
public int isMandotory { get; set; }
public Subject subject { get; set; }
}
class unitHelper
{
public List<unit> result { get; set; }
}
用户将能够在组合框中选择主题,因此我希望它返回主题,以便我可以根据主题动态加载单位。
有人请帮我这样做.. 任何形式的帮助都表示赞赏......
答案 0 :(得分:1)
您需要稍微更改一下代码。
<ComboBox x:Name="cmbSubjects" HorizontalAlignment="Right" Background="#FFE5DBE8" Width="141" SelectedItem="Maths" Margin="0,217,957,247" PlaceholderText="Select"> <ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding name}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
并按如下方式设置itemssource:
cmbSubjects.ItemsSource=data.Result;
然后在SelectionChanged事件中
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Subject selectedSubject = cmbSubjects.SelectedItem as Subject;
if(selectedSubject!=null){
int selectedSubID = selectedSubject.ID;}
}
答案 1 :(得分:0)
Combobox有一个SelectionChanged
事件,您可以在选择新项目时从组合框中捕获所选项目,在该事件触发器中,您可以捕获对象并传递ID。
修改后,在XAML
中添加SelectionChanged
属性后,您的组合框将如下所示
<ComboBox x:Name="cmbSubjects" HorizontalAlignment="Right" Background="#FFE5DBE8" Width="141" SelectedItem="Maths" Margin="0,217,957,247" ItemsSource="{Binding Source={StaticResource cvsSubjects}}" PlaceholderText="Select" SelectionChanged="ComboBox_SelectionChanged"/>
你的代码将是
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Subject selectedSubject = cmbSubjects.SelectedItem as Subject;
int selectedSubID = selectedSubject.ID;
}