The instance of the class is a private member of the view code exposed as a public property named "ViewModel".
Asked
Active
Viewed 114 times
0
-
Without looking, I can definitely say, "I don't know." But I do know who does know--Snoop. Get it and use it to debug your bindings at runtime. – Apr 23 '15 at 17:04
-
Fools gonna fool. Sorry about that. – Oct 15 '15 at 19:23
2 Answers
2
You are setting the DataContext of the Grid to a string equal to "ViewModel". You need to make sure the DataContext property is correctly set to actual ViewModel
object instance, either with a binding or via code behind.
For more information, see my answer to the question What is DataContext for?
-
-
If you bind the `ViewModel` property, be sure the parent's DataContext is set to an object that contains the `.ViewModel` property. Typically I will set my application's .DataContext in the code behind (something like `MyApplicationWindow.DataContext = new ApplicationViewModel();`), and have everything else use bindings or implicit data templates to inherit their .DataContext from there. The solution [posted by octavioccl](http://stackoverflow.com/a/29826915/302677) would also work, although I personally prefer to avoid defining the data context as a static resource in the XAML like that – Rachel Apr 23 '15 at 15:03
-
Thank you, Rachel. I think I prefer to have an instance of the ViewModel DataSource in the code behind as well. – Justin McCarthy Apr 23 '15 at 15:13
0
I'm agree with the Rachel's answer. An easy way to set the DataContext
of your Grid
could be this:
<Window.Resources>
<YourNamespace:ViewModel x:Key="ViewModel"/>
</Window.Resources>
<Grid DataContext="{StaticResource ViewModel}">
<TextBox Text="{Binding Path=TestName}" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="TextBox1" VerticalAlignment="Top" Width="479" />
</Grid>
This way you don't need to touch the code behind of your Window
/UserControl
.
If you don't want to change the code in your view and and want to keep your ViewModel
property, then you could also do this:
Public Class View Inherits Window
Private m_ViewModel As ViewModel
Public Property ViewModel() As ViewModel
Get
Return m_ViewModel
End Get
Set
m_ViewModel = Value
End Set
End Property
Public Sub New()
InitializeComponent()
ViewModel = New ViewModel()
DataContext = ViewModel
End Sub
End Class
So you don't need to set the DataContext
in your view, just do this:
<Grid>
<TextBox Text="{Binding Path=TestName}" Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="TextBox1" VerticalAlignment="Top" Width="479" />
</Grid>

ocuenca
- 38,548
- 11
- 89
- 102