2011-02-25 76 views
1

我想从itemssource中预先选择一个组合框(选择一个现有项目)。这是我的类模型和xaml语法。WPF Combobox - 预选项目

Class ViewModelSample 
{ 
Public List<Animal> Animals; 
Public LivingBeing LivingBeingInst {get; set;} 
} 

Class LivingBeing 
{ 
    Public Animal AnimalInst {get; set;} 
} 

-------------------------------------------------------------------- 
<Combobox ItemsSource={Binding Animals} SelectedItem={Binding LivingBeingInst.AnimalInst} 
DisplayMemeber = SomePropertyInAnimal> 
-------------------------------------------------------------------------- 

但这并不奏效。我想要的是,当xaml出现时,我需要使用SelectedItem中给出的项目预先选择组合框。

任何帮助,非常感谢。谢谢你,玛尼

回答

2

通常情况下,你的ViewModel和SelectedAnimal属性有一个List(在你的情况下为动物),就你的情况而言,LivingBeingInst属性应该是列表中的选定动物。

为了得到像这样的工作,你可能需要编写一些代码来将LivingBeing转换成动物并通过ValueConverter返回。

但是,我相信你最好的选择是创建一个SelectedAnimal属性来存储选定的动物。

在您的构造函数或最初填充动物列表的位置,您可以将SelectedAnimal设置为列表中的第一个元素。

+0

不,我已将SelectedItem设置为LivingBeingInst.AnimalInst。这里不需要任何转换器。 AnimalInst是列表中的值之一,但组合框仍然默认不显示selecteditem。 – 2011-02-26 00:08:19

+0

转换器在这里没有帮助。需要预先选择的“动物”实例需要在“动物”集合中进行预选。 – 2015-04-20 15:51:00

0

您没有在这些类中实施更改通知。所以除非你在相应类的构造函数中填充了所有这些属性,否则绑定无法知道你已经这样做了。

至少,这是我从你发布的非工作的,不可编译的,不是真的代码的猜测。一般来说,如果您发布实际代码,您会得到更多有用的答案,特别是如果您花时间实施仍然存在您尝试解决的问题的现有代码的最小最小子集。 (除此之外,当你这样做时,你可能会自己找到答案。)

+0

感谢您的输入,我解决了这个问题。我实施了INotifyPropertyChanged,但那不是问题。组合框的SelectedItem应该是ItemsSource中给出的COllection中的一个值。虽然AnimalInst是Animal类型,但它不是ItemsSource中的对象之一。所以我做的是, – 2011-02-27 15:10:10

+0

是的,那是另一种可能性。您会注意到,无法从您发布的代码中知道这是问题所在。 – 2011-02-27 20:05:50

3

感谢您的输入,我解决了这个问题。我实施了INotifyPropertyChanged,但那不是问题。

组合框的SelectedItem应该是ItemsSource中给出的集合中的一个值。虽然AnimalInst是Animal类型,但它不是ItemsSource中的对象之一。所以我做的是,宣布SelectedAnimal属性,将其绑定到SelectedItem。 “SelectedAnimal”将从“Animals”集合中比较AnimalInst.Name返回相同的实例。如下所示。 (时间表是收集)。

private ISchedule _selectedSchedule; 
     public ISchedule SelectedSchedule 
     { 
      get 
      { 
       if(_selectedSchedule != null) 
       { 
        var schedule = this.Schedules.Where(item => item.GlobalCodesId == _selectedSchedule.GlobalCodesId).FirstOrDefault(); 
        return schedule; 
       } 
       return _selectedSchedule; 
      } 
      set 
      { 
       _selectedSchedule = value; 
       base.NotifyPropertyChanged("SelectedSchedule"); 
      } 
     } 
+0

我认为这几乎是我说的。 – SergioL 2011-02-28 15:27:34

1

SelectedItem的初始值必须是一个对象,它是的组合框的ItemsSource一个构件的一个实例。在此示例中,LivingBeingInst.AnimalInst需要位于Animals集合中。

您还可以找到Animals集合中LivingBeingInst.AnimalInst相应项目的属性,例如Everything Matters的答案的确如此。