简体   繁体   中英

How to use dynamic DataType in c#?

Honestly, I don't know how to ask this one. Let me explain my scenario first.

From the answer that I have got from my last question:

...
var frame = sender as Frame;
UserControl1 uc1 = frame.Content as UserControl1;
MainViewModel mvm = uc1.DataContext as MainViewModel;
...

As you can see frame.Content changes and it can have different DataType. Therefore, I can't just write UserControl1 . Now, what can I write as replacement for UserControl1 ?

Update: Added details

  • frame.Content is changing upon user interaction
  • I want to determine the current DataType of the DataContext of frame.Content during runtime

As always, please tell me if you want clarification.

If the only thing you need out of frame.Content is a DataContext you may try casting it to FrameworkElement , eg:

var frame = sender as Frame;
FrameworkElement content = frame.Content as FrameworkElement;
MainViewModel mvm = content.DataContext as MainViewModel;

If frame.Content is not always a FrameworkElement you may want to check that first:

var frame = sender as Frame;
FrameworkElement content = frame.Content as FrameworkElement;
if (content != null) {
    MainViewModel mvm = content.DataContext as MainViewModel;
    // work with mvm...
}
else {
    // Frame's content is something unexpected.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM