简体   繁体   中英

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 - 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 (ie actual path it expects is ProductCollection.AmendProduct).

that's why it works in the first one. DataContext works on the Scope basis (ie 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, eg, 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.)

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