WPF DataContext and ICommand withn MVVM
I've connected up my button click in my xaml file, I then wanted to bind some text boxes contained in a StackPanel to my collection.
If I set the DataContext of the StackPanel the button click no longer works; however if I set the DataContext on each TextBox the button click works as before. I've not idea whyy...
this markup works
<StackPanel>
<TextBlock>Product Name</TextBlock>
<TextBox Width="200" DataContext="{Binding Path=ProductCollection, Mode=TwoWay}" Text="{Binding Path=ProductName, Mode=TwoWay}"></TextBox>
<TextBlock>Unit Price</TextBlock>
<TextBox Width="200" DataContext="{Binding Path=ProductCollection, Mode=TwoWay}" Text="{Binding Path=UnitPrice, Mode=TwoWay}"></TextBox>
<Button Margin="20" x:Name="UpdateProduct" Content="Update Product" Command="{Binding AmendProduct}" />
</StackPanel>
this markup does not work开发者_StackOverflow - I've moved the DataContext to the stack panel.
<StackPanel DataContext="{Binding Path=ProductCollection, Mode=TwoWay}">
<TextBlock>Product Name</TextBlock>
<TextBox Width="200" Text="{Binding Path=ProductName, Mode=TwoWay}"></TextBox>
<TextBlock>Unit Price</TextBlock>
<TextBox Width="200" Text="{Binding Path=UnitPrice, Mode=TwoWay}"></TextBox>
<Button Margin="20" x:Name="UpdateProduct" Content="Update Product" Command="{Binding AmendProduct}" />
</StackPanel>
when you put the DataContext to StackPanel, it expects AmendProduct to the be in the PathCollection (i.e. actual path it expects is ProductCollection.AmendProduct).
that's why it works in the first one. DataContext works on the Scope basis (i.e. heirarchy)
For MVVM, people typically provide an entire class dedicated to being the "view model" for the entire control, so you usually wouldn't be setting a new DataContext within the control. The view model will expose exactly the properties that are needed by the view, e.g., ProductName, UnitPrice, etc.
The control that created this one that you're showing might set the DataContext for this control. (And you might do the same recursively for other custom controls you create.)
精彩评论