2010-06-09 158 views
0

我是Wpf世界的新手,所以我創建了幾個視圖,它們都有至少一個ComboBox,因爲我使用的是MvvM模式,所以我一直在重新輸入相同的代碼行來填充組合,並獲得SelectedItem(創建屬性,私人和其他獲得)。Wpf Mvvm組合框

是否有某種框架可以改進這部分?或破解/技巧?因爲我看到太多重複的代碼......也許是我做錯了什麼,一起來看看:

XAML:

<ComboBox name= "cbDepartments" DisplayMemberPath="DepartmentName" 
         SelectedValuePath ="PrimaryKey" 
         ItemsSource="{Binding Path=Departments}" 
         SelectedItem="{Binding Path=DefaultBranch,Mode=TwoWay}" 
> 

視圖模型:

private Department defaultBranch; 
     public Department DefaultBranch 
     { 
      get 
      { 
       return this.defaultBranch; 
      } 

      set 
      { 
       if (this.defaultBranch != value) 
       { 
        this.defaultBranch = value; 
        this.OnPropertyChanged("DefaultBranch"); 
        this.saveChangeCommand.RaiseCanExecuteChanged(); 
        this.UserMessage = string.Empty; 
       } 
      } 
     } 

private ObservableCollection<Department> departments; 
public ObservableCollection<Department> Departments 
     { 
      get { return this.departments; } 
      set 
      { 
       if (this. departments!= value) 
       { 
        this. departments = value; 
        this.OnPropertyChanged("Departments"); 
       } 
      } 
     } 
+0

它是同類ComboBox(也就是說,你是否有多個組合框分散在整個應用程序中?)如果是這樣的話 - 你可以製作一個自定義控件,該組件具有這種標記並繼承自ComboBox – Goblin 2010-06-09 19:55:14

+0

@Goblin,感謝您的建議,但是我試圖在wpf中自定義一個控件,發現並不像在winform的世界中那麼容易... – 2Fast4YouBR 2010-06-10 14:36:10

回答

1

大多數的你有什麼小艾標準。有幾件事情,你可以砍掉:

  • 它看起來像您不使用的SelectedValue這樣可以去掉SelectedValuePath
  • 的SelectedItem是雙向默認情況下,這樣你就可以從結合
  • 刪除模式=雙向
  • 對於部門屬性,您應該可以完全移除設置器,而是添加和移除現有集合中的項目。這也可以幫助避免ItemsSource綁定無法獲得正確通知的問題 - INotifyCollectionChanged在集合屬性上工作得更加一致,即INotifyPropertyChanged。部門可以向下摺疊至:

公衆的ObservableCollection <部>部門{獲得;私人設置; }

+0

謝謝約翰,我不知道INotifyColletion,我會挖掘以找出答案,歡呼。 – 2Fast4YouBR 2010-06-10 14:38:44

+0

ObservableCollection爲你實現了INotifyCollectionChanged,所以只要你使用它,你可以在集合中的項目集被修改時免費得到通知。 – 2010-06-10 22:15:03

0

,作爲使與部門的組合框的自定義控制 - 這是很容易在WPF:

<ComboBox DisplayMemberPath="DepartmentName" x:Class="...DepartmentComboBox" 
      SelectedValuePath ="PrimaryKey" 
      ItemsSource="{Binding Path=Departments}" 
      SelectedItem="{Binding Path=DefaultBranch,Mode=TwoWay}"/> 

和代碼隱藏:

public partial class DepartmentComboBox 
{ 
    public DepartmentComboBox() 
    { 
     InitializeComponent(); 
    } 
}