I’m having problems setting the DataContext for all fields that are inside a stackPanel. What I would like to do is set the Data Context as vm:ViewModel. But it’s not working and when I ask VS for assistance with DataBinding it Displays the TextBox.DataContext inside the TextBox. Is there a way to only set it once or do I have to set it for each control?
<StackPanel DataContext="vm:ViewModel">
<TextBox Text="{Binding FirstNumber}" HorizontalAlignment="Left" Height="23" Margin="206,45,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120">
<TextBox.DataContext>
<vm:ViewModel/>
</TextBox.DataContext>
</TextBox>
</StackPanel>
You need to get your DataContext to refer to an instance of your ViewModel.
DataContext="vm:ViewModel"is not creating an instance of the ViewModel…it’s just setting a string.Use Property Element syntax instead:
And if you do that, then there’s no need/in fact it’s probably wrong to create another one in your TextBox.DataContext…you just want to inherit the DataContext of the StackPanel.
I’ll just show you another way to create a ViewModel and to refer to the instance of it so you have a bigger picture…..that is to create it in resources, and then refer to that resource in the binding…here’s an example:
Another example that sets the DataContext at a higher level in the tree: