imagine the following simple Models (an example for simplicity, we actually have MVVM, but that doesn't matter):
public class User { public string Username { get; set; } } public class StackOverflowUser : User { public int Reputation { get; set; } }
Now we have a Silverlight UserControl that contains the following Controls (again, this is just an example, split up to the kernel):
<Grid> <TextBlock Text="Username:" /> <TextBlock Text="{Binding Path=Username}" /> <TextBlock Text="Reputation:" /> <TextBlock Text="{Binding Path=Reputation}" /> </Grid>
Now I would like this UserControl be compatible with both models, User and StackOverflowUser . I can set the UserControl DataContext either User or StackOverflowUser Type:
this.DataContext = new User { Username = "john.doe" };
If set to StackOverflowUser , everything works fine. If set to User , I get the "BindingExpression Path" error because the Reputation property is not in the User model. Which I fully understand.
Is there a way 1) to avoid this exception and 2) to control the visibility of controls, collapse when the associated property is unavailable?
Of course, we prefer an elegant solution in which the problem is solved by setting up the Binding Expression expression and / or using converters, etc. and if possible, avoid tons of code.
Thanks in advance for your help and suggestions,
best wishes,
Thomas