简体   繁体   中英

XAML DataContext and ViewModel Type

I use MVVM for my application, the DataContext of controls is assigned in my c# code (not in XAML).

Therefore the XAML controls have no idea to which instance type its DataContext is set to. The consequence is that there is no refactoring support and intellisense for the bound properties of my viewmodel in XAML.

Is there a way to tell a control in XAML to which type its DataContext is linked?

So when I modify a property name in my ViewModel or search for all references of that property, I want that this property in XAML bindings gets considered too.

There is no framework support, the best you can do is tell the VS designer the 'shape' of the DataContext so that it will give you hints for the properties. If you want to make your solution more refactor-proof, I would recommend Daniel's T4 metadata solution:

http://www.codeproject.com/KB/codegen/T4Metadata.aspx

This generatesmetadata for your view models which you can reference in the XAML:

<StackPanel DataContext="{Binding Source={StaticResource Person}}">
   <TextBlock >Name:</TextBlock>
   <TextBox Text="{Binding Path={x:Static Metadata:PersonMetadata.NamePath}}"/>
</StackPanel>

Colin E.

不,因为DataContext可以在运行时更改,所以将它绑定到特定类型是没有意义的。

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