2012-08-02 144 views
0

我有一個組合框,其XAML如下所示:在組合框顯示的默認值

<StackPanel Grid.Row = "0" Style="{DynamicResource chartStackPanel}"> 
     <Label Content="Port:" HorizontalAlignment="Left" Margin="8,0,0,0"/> 
     <ComboBox Width="75" Height="24" HorizontalAlignment="Right" Margin="8,0,0,0" SelectedValue="{Binding Port, Mode=OneWayToSource}"> 
      <ComboBoxItem Content="C43"/> 
      <ComboBoxItem Content="C46" IsSelected="True"/> 
      <ComboBoxItem Content="C47"/> 
      <ComboBoxItem Content="C48"/> 
     </ComboBox> 
    </StackPanel> 

上面提到的樣式定義如下:

當ComboBox首先顯示,我想要在ComboBox中顯示'C46'項目。但是,加載時,組合框是空白的。有趣的是,我的虛擬機中的源屬性設置爲'C46'。任何人都可以告訴我做錯了什麼?

+0

您是否知道'SelectedItem'和'SelectedValue'之間的區別? (另請參見'SelectedValuePath') – 2012-08-02 19:19:15

回答

1

你提到你有您的ViewModel中的源集合。因此,爲什麼在XAML中指定ComboBoxItems?我認爲你應該有你的ViewModel項目集合屬性和SelectedItem屬性。在構造函數中,您可以設置SelectedItem。它可以看起來如下:

public ObservableCollection<MyClass> Items { get;set; } 

public MyClass SelectedItem 
{ 
    get {return this.selectedItem;} 
    set { 
     this.selectedItem = value; 
     RaisePropertyChanged("SelectedItem"); 
     } 
} 

而且在構造函數後的項目屬性初始化:

this.SelectedItem = Items[x] 

你的XAML可以看起來則如下:

<ComboBox Width="75" Height="24" HorizontalAlignment="Right" Margin="8,0,0,0" 
         ItemsSource="{Binding Items}" 
         SelectedItem="{Binding Path=SelectedItem}" 
         DisplayMemberPath="Content"/> 
0

我按照相同的方式,它顯示屏幕加載時'C46'。 但是,虛擬機將顯示System.Windows.Controls.ComboBoxItem: C46代替C46因爲你沒有使用SelectedValuePath特定的綁定值路徑

我用SelectedValuePath="Content"它會顯示「C46」

+0

虛擬機中的任何更改如何反映在這裏都不是問題。當用戶更改端口時,更改將反映在虛擬機中,我可以適當地處理它。我只是不明白爲什麼當我的表單第一次加載時沒有顯示。 – 2012-08-02 19:28:12

-2

//查看

<ComboBox x:Name="cbCategories" Width="300" Height="24" ItemsSource="{Binding Categories}" 
DisplayMemberPath="CategoryName" SelectedItem="{Binding SelectedCategory}" /> 

// ViewMode l

private CategoryModel _SelectedCategory; 
     public CategoryModel SelectedCategory 
     { 
      get { return _SelectedCategory; } 
      set 
      { 
       _SelectedCategory = value; 
       OnPropertyChanged("SelectedCategory"); 
      } 
     } 

     private ObservableCollection<CategoryModel> _Categories; 
     public ObservableCollection<CategoryModel> Categories 
     { 
      get { return _Categories; } 
      set 
      { 
       _Categories = value; 
       _Categories.Insert(0, new CategoryModel() 
       { 
        CategoryId = 0, 
        CategoryName = " -- Select Category -- " 
       }); 
       SelectedCategory = _Categories[0]; 
       OnPropertyChanged("Categories"); 

      } 
     }