2014-07-04 2 views
0

ViewModel의 속성 설정을 기반으로 UserControl을 전환하려면 어떻게해야합니까?속성을 기반으로 UserControl을 전환하십시오.

경우 Vm.View = "A"

<Window> 
<local:UserControlA/> 
</Window> 

Vm.View = "B"는

<Window> 
<local:UserControlB/> 
</Window> 

Vm.View 언젠가 C, D를 허용 할 수 열거 인 경우, 및 곧. 두 UserControls 모두 동일한 Vm에 바인딩되지만 사용자의 입력에 따라 근본적으로 다른 데이터를 제공합니다. 그래서 타입 기반의 DataTemplate은 실제로 여기서 작동하지 않습니다.

생각하십니까?

답변

1

당신이 DataTriggers를 사용 ContentTemplate입니다 설정할 수 있습니다 View 값에 ContentControl 창 내부 및 기반 추가합니다.

<ContentControl Content="{Binding}"> 
    <ContentControl.Style> 
     <Style TargetType="ContentControl"> 
      <Setter Property="ContentTemplate"> 
       <Setter.Value> 
        <DataTemplate> 
         <local:UserControlA/> 
        </DataTemplate> 
       </Setter.Value> 
      </Setter> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding View}" Value="B"> 
        <Setter Property="ContentTemplate"> 
         <Setter.Value> 
          <DataTemplate> 
           <local:UserControlB/> 
          </DataTemplate> 
         </Setter.Value> 
        </Setter> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style> 
    </ContentControl.Style> 
</ContentControl> 
+0

이것은 컨트롤 스위치가 작동하지만 UserControls에서 vm 데이터를 표시하지 않는 경우 작동합니다. 바인딩이 작동하지 않는 이유가 궁금합니다. –

+0

신경 쓰지 마세요. 그것을 알아 냈다. ContentControl Content = {Binding} –

+1

같은 내용을 게시하려고했습니다. ContentControl의 템플릿에는 ContentControl의 Content 속성이 DataContext로 있으므로 Content를 VM을 가리 키도록 설정해야합니다. –

0

당신은 DataTemplateDataType 속성을 활용하고 바인딩 엔진이 알아서 할 수 ...

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; 
    } 
관련 문제