tig tig - 1 year ago 68
C# Question

How do I override the ViewModel DataContext so I can bind to objects in the View (Mvvm-Light)?

I am using Mvvm-Light and have been ignoring how binding in XAML really works up until now.

Here's my XAML


<Grid x:Name="LayoutRoot" Background="Transparent">

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,14">
<TextBlock x:Name="ApplicationTitle" Text="{Binding SecuritySystemName}" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="{Binding PageName}" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

<TextBlock Name="textCode"
DataContext="{WHAT GOES HERE to bind to properties on my View (SecurityPanelPage class)}"
Text="{Binding Path=Code}" />


{Binding SecuritySystemName} and {Binding PageName} correctly bind to my ViewModel (SecuirtyPanelViewModel). But I want {Binding Code} in the TextBlock element to bind to my VIEW (not ViewModel).

I have searched and searched for documentation & samples that explain the syntax and values supported by DataContext and Binding. Nothing has helped.

All I want to know is how do I set a DataContext (or specify something in a {Binding ...} that will point to my View object. I've tried "Self" and all sorts of "RelativeSource" things, but none work. Guessing is not productive because the round trip into the debugger before the XAML is parsed is too long.


UPDATE - I found AN answer that gets me moving, but I still don't grok so I have follow up questions for the fine posters below..

Here's what works:

<phone:PhoneApplicationPage x:Name="ThisPage">
<TextBlock Name="textCode" Text="{Binding Code, ElementName=ThisPage"/>

I found this hint here: http://bursjootech.blogspot.com/2007/12/bind-from-xaml-to-local-property-in.html

He asked the question differently: how to "Bind from XAML to a local property in code-behind".

I still don't understand the two solutions provided below. So more questions below...

Answer Source

Typically when you're using MVVM nearly all of your bindable properties are on your ViewModel and not on your Views. However, obviously sometimes you want to create component controls which do have properties. Can you explain what the property is and why it needs to only be a property on the view?

That being said ... I'm guessing your SecurityPanelPage is the view for the XAML displayed?

You can give your control a name and then use ElementName binding. This way you do not need to set the DataContext.


And then your binding changes to:

  Text="{Binding Path=Code, ElementName=controlName}" />

To explicitly set the DataContext you can do the following:

  DataContext="{Binding ElementName=controlName}"
  Text="{Binding Path=Code}" />
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download