gpt4 book ai didi

c# - ComboBox 与 ObservableCollection 绑定(bind)

转载 作者:行者123 更新时间:2023-12-02 22:35:10 25 4
gpt4 key购买 nike

我的任务是将组合框添加到现有的 WPF 表单中。我从未使用过 WPF,我很迷茫,特别是在绑定(bind)和使用 ObservableCollection 属性方面。所有示例都与我被告知的方式完全不同。

我最初的组合框是这样设置的:

<ComboBox Name="GroupComboBox" Width="132" Height="22" Grid.Column="0" Grid.Row="3" Margin="0,30" VerticalAlignment="Top" >         
<ComboBoxItem Content="Data Warehouse"></ComboBoxItem>
<ComboBoxItem Content="KPI"></ComboBoxItem>
<ComboBoxItem Content="Failures"></ComboBoxItem>
<ComboBoxItem Content="All Groups"></ComboBoxItem>
</ComboBox>

效果很好。这是当我被告知我必须摆脱所有 ComboBoxItem 内容并将组合框绑定(bind)到 ObservableCollectionGroups 和 ObservableCollectionSelectedGroups 时,为此我所要做的就是将其添加到 ViewModel 类:

 public ObservableCollection<string> Groups { get; set; }      

public ObservableCollection<string> SelectedGroups { get; set; }

好的,所以我将上面的内容添加到 View 模型类中,如下所示:

public class ClioViewModel : INotifyPropertyChanged
{
public ObservableCollection<string> Groups { get; set; }

public ObservableCollection<string> SelectedGroups { get; set; }
}

(本类(class)中已经有很多其他内容,但出于时间和空间的考虑,我没有发布它。如果需要,我很乐意根据要求添加更多内容)

然后我将我的 xaml 更改为如下所示:

<ComboBox Name="GroupComboBox" ItemsSource="{Binding Groups}" SelectedItem=" Binding  SelectedGroups, Mode=TwoWay}" Width="132" Height="22" Grid.Column="0" Grid.Row="3" Margin="0,30" VerticalAlignment="Top" >                         
</ComboBox>

这没有用。当然没用!我还没有在我的组合框中列出任何我想要的项目!问题是,如果它们不属于 comboBox 的内部并且没有放在 Group/Selected 组属性中,那么它们到底去哪儿了?我见过的众多组合框绑定(bind)示例中没有一个看起来像我被告知要做的那样。

如果有人能告诉我我所缺少的东西,我将不胜感激。

最佳答案

您需要将值添加到您的 Group 集合中的某处(我会说是在初始化程序或类构造函数中):

Groups.Add("Data Warehouse");
Groups.Add("Data KPI");
Groups.Add("Data Failures");
Groups.Add("Data All Groups");

坦率地说,我不认为在这种情况下这样做有什么意义,但这可能与您的其余代码有关。

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

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