开发者

self referencing xaml file

I am using the Model View ViewModel pattern in my WPF application. The DataContext of my view is set to the ViewModel.

I have a ListView in my view, which has a ContextMenu and one of the MenuItems there needs to bind to a Command and the CommandParameter is the ListView itself.

Now my problem is, that I don't know how to reference the ListView. Maybe a code-snippet makes it easier to understand:

<ListView 
            Name="lvTestList"
            ItemsSource="{Binding Path=TestList.Items}">

            <!-- Context Menu of the selected test -->
            <ListView.ContextMenu>
                <ContextMenu>
                    <MenuItem
                        Header="Remove from List"
                        IsEnabled="{Binding IsATestSelected}" 
                        Command="{Binding RemoveTestFromTestListCommand}" 
                        CommandParameter="{Binding ElementName=lvTestList}"/>
                </ContextMenu>
            </ListView.ContextMenu>

            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding TestName}"/>
                    <GridViewColumn Header="Package" DisplayMemberBinding="{Binding PackageName}"/>
                    <GridViewColumn Header="Expected Duration" DisplayMemberBinding="{Binding ExpectedDuration}"/>
                </GridView>
            </ListView.View>
        </ListView>

The problematic line is the one saying:

CommandParameter="{Binding ElementName=lvTestList}"/>

Normally, this would be working. However, if the DataContext of the whole class changes, it just passes null as parameter.

Does anyone know how to keep a reference to the current xaml document? or how to "talk" to the ListView "lvTestList" dire开发者_如何学Pythonctly?

Best wishes and Thanks for help, Christian


Use Self Binding:

CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Parent.PlacementTarget.Name}"

Will set CommandParameter's value to "lvTestList".

You can also use Ancestor Binding:

CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}, Path=PlacementTarget.Name}"

In these examples, PlacementTarget will be a control on which a ContextMenu was opened. In your case, it will be ListView.


You can obtain a reference to your ListView via a reltivesource FindAncestor binding:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}

It seems a bit odd that you want to pass a ListView as a parameter to a command, perhaps you should use:

{Binding Path=DataContext.Something, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListView}}

With the path set to the DataContext you are then able to bind the parent view model.

Hope that helps, Colin E.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜