开发者

How to use Nested Views in WPF MVVM

Hi I am trying to understand the best practise to use nested views.

I have an 'Attribute' View which is bound to collection of name value pairs in the 开发者_如何学Cview model. I need to reuse this at various places in my UI.

I have another 'Condition View' which has a string property and Dictionary(string,string) collection. I tried to create a text box and add the Attribute View control in the XAML

    <StackPanel>
        <StackPanel Orientation="Horizontal">
            <Label Content="{x:Static l:StringResources.ConditionViewLabelText}" />
            <TextBox Text="{Binding Type,Mode=TwoWay}" Width="100" />
        </StackPanel>
        <vw:AttributeView />
    </StackPanel>

I want to bind the AttributeView's bound property to the Dictionary(string,string)'s collection property of the parent view model. Whats the best way to do it. I am not able to bind the vw:AttributeView to a ConditionViewModels ?

Can you please let me know the best practise to do this?

-- EDIT Please find my AttributeView (This is the child view's xaml code). The data template is bound to an observable collection on the AttributeViewModel

 <StackPanel>
        <ItemsControl ItemsSource="{Binding AllAttributes}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Width="100" Text="{Binding Name, Mode=TwoWay}" Margin="5,0,5,0" />
                        <TextBox Width="100" Text="{Binding Value, Mode=TwoWay}" Margin="5,0,5,0" />
                        <TextBlock Width="100" Text="{Binding KeyValue, Mode=OneWay}" />
                        <Button Width="50" Content="{x:Static l:StringResources.AttributeViewButtonDeleteText}" Command="{Binding Path=DataContext.DeleteAttribute, ElementName=AttributeControl}" CommandParameter="{Binding Name}"></Button>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
        <Button Name="btnSomething" Content="{x:Static l:StringResources.AttributeViewButtonAddText}" Command="{Binding AddNewAttribute}" />
    </StackPanel>
</Grid>


Based on your comments that your parent / child relationship is not reflected in your view model, you have two options:

  1. Create the relationship in your view model to reflect the relationship in your view, allowing you to navigate from the parent to the child and vice-versa should you need this.
  2. Use a RelativeSource FindAncestor binding to navigate up the visual tree and locate a control bound to the parent view model, biding to this controls DataContext.

Option (2) will make you look clever, but option (1) is much simpler!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜