당신은 DataTemplate
의 DataType 속성을 활용하고 바인딩 엔진이 알아서 할 수 ...
XAML
<Window.Resources>
<DataTemplate DataType="localEnums:ProduceType.Apples">
<local:ApplesView />
</DataTemplate>
<DataTemplate DataType="localEnums:ProduceType.Oranges">
<local:OrangesView />
</DataTemplate>
</Window.Resources>
<StackPanel>
<ContentPresenter Content="{Binding ProduceType}" />
<Button Content="Change Produce" Click="Button_Click"/>
</StackPanel>
보기 모델
public class ProduceViewModel : ViewModel
{
public ProduceViewModel()
{
this.ProduceType = ProduceType.Apples;
}
private ProduceType _produceType;
public ProduceType ProduceType
{
get
{
return _produceType;
}
set
{
if (_produceType != value)
{
_produceType = value;
RaisePropertyChanged();
}
}
}
}
버튼 처리기를 클릭합니다 (순수 MVVM을 위반하지만 DataTemp을 보여 주기만하면됩니다.). 늦은 전환)
private void Button_Click(object sender, RoutedEventArgs e)
{
(this.DataContext as ProduceViewModel).ProduceType = ProduceType.Oranges;
}
이것은 컨트롤 스위치가 작동하지만 UserControls에서 vm 데이터를 표시하지 않는 경우 작동합니다. 바인딩이 작동하지 않는 이유가 궁금합니다. –
신경 쓰지 마세요. 그것을 알아 냈다. ContentControl Content = {Binding} –
같은 내용을 게시하려고했습니다. ContentControl의 템플릿에는 ContentControl의 Content 속성이 DataContext로 있으므로 Content를 VM을 가리 키도록 설정해야합니다. –