开发者

MVVM: How to avoid adding DataContext to Xaml for Blend Support

We have a C# solution that is based on loose Xaml (or Hosted Xaml - have never been to sure of the correct term!). But basically we take a Xaml file and load it into a XamlReader and then pop that FrameworkElement onto a UserControl. We require the ability to handle data binding and we have a ViewModel that takes care of this. However, although I can inject the DataContext through code by setting it on the newly created FrameworkElement, if I want to work easy through Blend and use the built in list of bindable properties when you select the 'Data Binding..." option on a property I need to have set the DataContext right there in the Xaml (if not Blend will add it to the Xaml). I'd rather not have to do this because as I say I am doing this through code already.

The question is - Is there any way to avoid this?

I was thinking of doing this somehow through the app.xaml but the problem is d开发者_C百科epending on the screen and when it is shown it will have a different context (so we dynamically change the context) and I'm pretty sure you can't load in multiple data contexts.

Maybe there's a better way of splitting this up. Our solution has the following: -

  • A WPF application with a MainWindow.xaml (the main application)
  • A User Control in a separate assembly that is placed on the MainWindow.xaml by the main WPF application (above)
  • This User Control is then bound to the View Model
  • The main application sets the DataContext as it goes through it's build in state machine.
  • All Loose Xaml files are held in the main application.

So basically depending on when the state machine displays a screen it will have a different Data Context. The State Machine handles pushing the Data Context and those screens will only work if they are used in the correct context. So we don't really need (or want) to have to set the data context in the Xaml. It done by the state machine.

But I haven't been able to find much info on the Tinterweb around Loose Xaml so we're pretty much learning as we go...

Thanks in advance!


Have you tried d:DataContext={d:DesignInstance ...} ? It allows you to define a DataContext for design time only, for Blend and VS.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜