저는 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"명령이 호출 될 것으로 예상되지만 하지만 그렇지 않습니다.
누구나 아이디어가 있습니까 ??? 큰 감사입니다.
UserControl의 datacontext는 어떻게 설정 되나요? 올바르게 바인딩하려면 ViewModel로 설정해야합니다. –
userControl 버튼을 감싸는 stackPanel 태그 안에 DataContext = "MyUserControlViewModel"을 추가했습니다. 여전히 작동하지 않습니다. – Liran