2

我的任务是向已经存在的 WPF 表单添加一个组合框。我从来没有使用过 WPF,我很迷茫,特别是在绑定和使用 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 内容并将组合框绑定到 ObservableCollectionGroups 和 ObservableCollectionSelectedGroups 时,我所要做的就是将其添加到 ViewModel 类中:

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

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

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

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

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

(这门课上还有很多其他的东西,但是为了时间和空间,我没有发布它。如果需要,如果需要,我很乐意添加更多内容)

然后我将我的 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>    

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

如果有人能启发我了解我所缺少的东西,我将不胜感激。

4

2 回答 2

3

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

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

坦率地说,在这种情况下,我没有看到这样做的意义,但它可能与您的其余代码有关。

于 2012-07-19T13:12:12.887 回答
2

就像大卫说的 - 填写您的群组收藏。第二:确保将DataContext设置为 viewmodel 的实例。您对 itemssource 的绑定是正确的。SelectedItem 的绑定不正确:您可以绑定到字符串属性。Mode = Twoway仅需要从ViewModel完成选择时就需要。

 public string MySelectedItem
 {
   get{return this._myselecteditem;}
   set{this._myselecteditem=value; OnPropertyChanged("MySelectedItem");}
 }

xml

  <ComboBox ItemsSource="{Binding Groups}" SelectedItem="{Binding MySelectedItem, Mode=TwoWay}"/>
于 2012-07-19T13:25:52.493 回答