How to use DataTemplateSelector with ContentControl to display different controls based on the view-model?

后端 未结 2 993
无人及你
无人及你 2021-01-17 04:52

I want to create a simple window that would display different controls (SpinEdit or TextEdit) based on the view-model that is selected.

I h

2条回答
  •  有刺的猬
    2021-01-17 05:10

    You do not need a DataTemplateSelector. WPF provides a mechanism that automatically selects a DataTemplate for the ContentTemplate of a ContentControl according to the type of a Content.

    As explained in Data​Template.​Data​Type:

    When you set this property to the data type without specifying an x:Key, the DataTemplate gets applied automatically to data objects of that type.

    So drop the x:Key value and your DataTemplateSelector, set DataType

    
        
            
        
        
            
        
    
    

    and bind the ContentControl's Content to a property that returns either a TInputValueVM or a TInputTextVM:

    
    

    The appropriate DataTemplate will now be selected automatically.

提交回复
热议问题