user668032
user668032

Reputation: 63

Override DataContext in WPF

I would like to make a UserControl which works only with a specific type of DataContext. For that purpose I am doing something like this:

  public new AutoSuggestViewModel DataContext 
             { get { return (AutoSuggestViewModel)base.DataContext; } 
               set { base.DataContext = value; } }

This unfortunately tends to break .Net's reflection and causes the control to error in design view in Visual Studio and even worse when I use the control as a part of DataGridTemplateColumn's editing template causes errors and does not work properly, again due to broken reflection. It comes out as AmbiguousMatchException on datagrid.BeginEdit()

Does anybody know a work around this problem and how to achieve that. And yes I have thought of using another property like MyDataContext which returns cast DataContext but I am looking for something more elegant if possible.

Upvotes: 1

Views: 504

Answers (2)

brunnerh
brunnerh

Reputation: 184727

There are other ways to ensure that the right kind of object is assigned, you can for example create a property changed callback in the overriden metadata, check the type of the new value and throw an exception if you "do not like it".

Upvotes: 0

Kent Boogaart
Kent Boogaart

Reputation: 178700

Something more elegant would be to not impose on the DataContext at all. In fact, it doesn't make any sense to me why you'd want to do that. Why not just define a separate dependency property that is of the correct type? Then, consumers of your control can assign to it, either through a binding to their data context, or using any other standard WPF idiom.

Upvotes: 2

Related Questions