Hello:
Recently, I asked for a way for selecting a view according to a data type for a ListView. I would never find the info about DataTemplateSelector.
Now I'm trying to do the same, but with a view within a ContentPage.
I didn't find any clue, so what I did was the next:
Having these models
public class BaseModel { public int type { get; set; }}
public class Data1Model : BaseModel { public int valueInt { get; set; }}
public class Data2Model : BaseModel { public string valueString { get; set; }}
I created a BaseModel variable on the ViewModel (with the private and public version, the OnPropertyChanged...).
So, I added this to the XAML:
XAML <ContentView x:Name="dataContentView" BindingContext="{Binding myBaseModel}" BindingContextChanged="ChangedBindingData"> </ContentView>
And wrote this on code behind:
CSHARP private void ChangedBindingData (object sender, EventArgs e) { Models.BaseModel data = (Models.BaseModel)dataContentView.BindingContext; switch (data.type) { case 2: dataContentView.Content = new Views.Data2View() { Margin = new Thickness(3), BindingContext = dataContentView.BindingContext }; break; default: dataContentView.Content = new Views.Data1View() { Margin = new Thickness(3), BindingContext = dataContentView.BindingContext }; break; } }
Amazingly, it works, but I don't think it's the right way to do it. I looked for another way to do it, with Templates or whatever other class that could help, but I didn't find any clue to follow. Maybe I'm not writting the right words in the search box, but the thing is, after several hours of searching, this is the best I can come up with.
So, am I right? Is there a better way to do it?
Thanks, and sorry for my 'newbiness' ^^U