可以';无法获取组合框的SelectedItem或SelectedIndex
本文关键字:SelectedItem SelectedIndex 组合 获取 可以 | 更新日期: 2023-09-27 18:29:51
我开始爬这里的墙了。我已经用项目列表填充了一个组合框,我正在努力找出哪个项目被选中了。我还试图将组合框设置为自动选择列表中的第0项。但这也不起作用,我在GroupIndex和SelectedGroup上都遇到了绑定表达式路径错误。但是我不知道问题出在哪里
组合框Xaml:
<ComboBox
Name="GroupComboBox"
SelectedIndex="{Binding Path=GroupIndex}"
SelectedItem="{Binding Path=SelectedGroup}"
DisplayMemberPath="Name"
SelectedValuePath ="Name"
ItemsSource="{Binding Path=Groups}"
Height="38"
HorizontalAlignment="Left"
Margin="159,115,0,0"
VerticalAlignment="Top"
Width="185"
FontSize="24" Text="Select a Group" IsEditable="False" IsReadOnly="False" />
这是填充组合框的代码。
void webService_GroupListChanged(string response)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
IList<JSONGroup> listOfGroups = new List<JSONGroup>();
listOfGroups = serializer.Deserialize<List<JSONGroup>>(response);
Application.Current.Dispatcher.BeginInvoke((Action)(() =>
{
Groups = new ObservableCollection<Group>();
foreach(JSONGroup group in listOfGroups)
{
Groups.Add(new Group(group.name, group.id));
}
}));
}
private int groupIndex;
private int GroupIndex
{
get { return this.groupIndex; }
set
{
if (this.groupIndex != value)
{
this.groupIndex = value;
this.OnPropertyChanged("GroupIndex");
}
}
}
private Group selectedGroup;
private Group SelectedGroup
{
get { return this.selectedGroup; }
set
{
if (this.selectedGroup != value)
{
this.selectedGroup = value;
this.OnPropertyChanged("SelectedGroup");
}
}
}
private ObservableCollection<Group> groups;
public ObservableCollection<Group> Groups
{
get { return this.groups; }
set
{
if (this.groups != value)
{
this.groups = value;
this.OnPropertyChanged("Groups");
}
}
}
- 若要在绑定中使用,
GroupIndex
和SelectedGroup
属性必须为public
- 不要同时设置
SelectedItem
和SelectedIndex
- 如果您更喜欢设置
SelectedItem
,那么Groups
中必须包含确切的项目(SelectedGroup
)