2011-02-11 4 views
0

저는 WPF에 익숙하지 않고 유명한 MVVM 패턴을 배우려고합니다. 간단한 명령을 바인드하려고하면 작은 문제 (저는 확신합니다)에 직면하게됩니다. 뷰 모델은사용자 정의 사용자 정의 컨트롤 내에서 명령 호출

이 내가 만든 간단한 UserControl을 수 있습니다 :

<UserControl x:Class="MVVM_UsingUserControl_Sample.View.MyUserControl" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300" 
      > 
     <StackPanel DataContext="MyUserControlViewModel" Orientation="Vertical" > 

     <Button Margin="0,100,0,0" Height="50" Width="50" Content="PressMe" Command="{Binding Path=MyCommand}"/> 

    </StackPanel> 

</UserControl> 

이은 사용자 컨트롤 뷰 모델

class MyUserControlViewModel : ViewModelBase 
{ 
     CommandBase m_MyCommand = null; 


     public MyUserControlViewModel() 
     { 

     } 

     public ICommand MyCommand 
     { 
      get 
      { 
       if (m_MyCommand == null) 
       { 
        m_MyCommand = new CommandBase(new Action<object>(DoSomething), 
                new Predicate<object>(CanDoSomething)); 
       } 

       return m_MyCommand; 
      } 
     } 

     public void DoSomething(object i_Params) 
     { 
      MessageBox.Show("Inside MyUserControl DoSomething"); 
     } 

     public bool CanDoSomething(object i_Params) 
     { 
      return true; 
     } 
} 

이있다 메인 창 XAML (아무 코드 behaind)입니다

지금 문제는 다음과 같습니다 와 아무것도 (스택 패널 내부에) 그대로 내 주요 창에있는 UserControl이 포함되어 있습니다. "MyButton"버튼을 눌렀을 때 "MyCommad"명령이 호출 될 것으로 예상되지만 하지만 그렇지 않습니다.

누구나 아이디어가 있습니까 ??? 큰 감사입니다.

+0

UserControl의 datacontext는 어떻게 설정 되나요? 올바르게 바인딩하려면 ViewModel로 설정해야합니다. –

+0

userControl 버튼을 감싸는 stackPanel 태그 안에 DataContext = "MyUserControlViewModel"을 추가했습니다. 여전히 작동하지 않습니다. – Liran

답변

2

주 창의 생성자에서 DataContext를 ViewModel로 설정하십시오. 예를 들어

, 당신의 XAML에서

this.DataContext = new MyViewModel(); 

, DataContext를 메인 창에서 상속 때문에

DataContext="MyUserControlViewModel" 

를 제거합니다.

모든 것이 예상대로 작동해야합니다.

+0

괜찮습니다. 기본 윈도우가 하나 이상의 컨트롤을 포함하고 있다면 설정해야합니까? 매번 포커스 된 컨트롤의 ViewModel에 따라 창의 DataContext ?? – Liran

+0

주 창에 둘 이상의 사용자 정의 컨트롤이있는 경우 주 창의 생성자에서 각 사용자 정의 컨트롤의 DataContext를 설정할 수 있습니다. 예를 들어 this.userControl1.DataContext = MyViewModel1; – ChrisNel52

관련 문제