question

antokhio-1226 avatar image
0 Votes"
antokhio-1226 asked ·

UWP - Switch Usercontrol depending on Property

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




windows-uwpwindows-uwp-xaml
xaml.txt (749 B)
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RichardZhang-MSFT avatar image
0 Votes"
RichardZhang-MSFT answered ·

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.

· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.