UWP - Switch Usercontrol depending on Property

antokhio 1 Reputation point
2019-11-29T09:05:58.827+00:00

i'm trying to implement an Widget, that consists of two UserControls.
So basic idea to have ViewModel for Page, and switch usercontrol depending on the Property:

        public class SearchViewModel : Observable  
        {  
            private object _selectedSearchMode;  
            public object SelectedSearchMode  
            {  
                get { return _selectedSearchMode; }  
                set { Set(ref _selectedSearchMode, value); }  
            }  
      
            private ICommand _searchModeClickedCommand;  
            public ICommand SearchModeClickCommand => _searchModeClickedCommand ?? (_searchModeClickedCommand = new RelayCommand(OnSearchModeClick));  
      
              
            public SearchViewModel()  
            {  
                this.SelectedSearchMode = new SearchBasicViewModel();  
            }  
      
            private void OnSearchModeClick(SearchModel obj)  
            {  
                if (this.SelectedSearchMode is SearchBasicViewModel)  
                    this.SelectedSearchMode = new SearchAdvancedViewModel();  
                else  
                    this.SelectedSearchMode = new SearchBasicViewModel();  
            }  
        }   

so the question is how to properly bind that in XAML:

xaml

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Richard Zhang-MSFT 6,936 Reputation points
    2019-12-02T02:28:55.827+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    For ContentControl you can use ContentTemplateSelector to achieve your requirements.

    We can create a selector class inherit the DataTemplateSelector

    public class SearchTemplateSelector : DataTemplateSelector
     {
         public DataTemplate BasicTemplate { get; set; }
         public DataTemplate AdvanceTemplate { get; set; }
         protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
         {
             if (item is SearchBasicViewModel)
             {
                 return BasicTemplate;
             }
             return AdvanceTemplate;
         }
     }
    

    Usage

    Due to some known issues in the forum, I cannot post XAML code, you can click this link to see the corresponding code.

    Thanks.

    0 comments No comments