2010-06-09 6 views
0

저는 Wpf 세계에서 새로운 편이어서 MvvM 패턴을 사용함에 따라 몇 가지보기를 만들었고 모두 하나 이상의 ComboBox를 가지고 있습니다. Combo를 채우고 SelectedItem을 가져 오는 동일한 코드 행 (속성 작성, 채우기 및 다른 항목 가져 오기).Wpf Mvvm ComboBox

이 부분을 개선 할 수있는 프레임 워크가 있습니까? 또는 해킹/속임수 ???

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

+0

@Goblin, 하지만 나 wpf에서 컨트롤을 사용자 지정하려고 시도하고 그 winform's 세계 에서처럼 쉽지 않다는 것을 알게되었습니다. – 2Fast4YouBR

답변

1

당신이 가지고있는 대부분의 꽤 같습니다

XAML :

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

의 ViewModel 나는 어쩌면 내가 뭔가 잘못하고있는 중이 야 ... 너무 많은 반복적 인 코드를 볼대로 봐 표준. 몇 가지가 있습니다 당신은 줄일 수 있습니다 : 당신이 SelectedValuePath을 제거 할 수 있도록 SelectedValue를 사용하지 않는 것처럼

  • 것 같습니다
  • 의 selectedItem 당신이이
  • 바인딩에서 모드 = 양방향을 제거 할 수 있도록 기본적으로 양방향입니다
  • departments 속성의 경우 setter를 완전히 제거하고 대신 기존 컬렉션의 항목을 추가 및 제거 할 수 있어야합니다. 또한 ItemsSource 바인딩이 올바른 알림을받지 못하는 문제를 피할 수 있습니다. INotifyCollectionChanged는 컬렉션 속성에서 INotifyPropertyChanged보다 일관되게 작동합니다. 부서가 아래로 붕괴 수 :

공공 ObservableCollection에 < 부> 부서 {얻을; 개인 집합; 코드 숨김

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

그리고 : -} 부서와 콤보 상자에 대한 사용자 지정 컨트롤을 만들기위한로서

+0

감사합니다 존, 나는 INotifyColletion에 대해 알지 못했습니다. – 2Fast4YouBR

+0

ObservableCollection은 사용자를 위해 INotifyCollectionChanged를 구현하므로 콜렉션의 항목 집합이 수정 될 때 무료로 알림을받습니다. –

0

는 그 WPF에 정말 쉽게

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