开发者

Bind to parent DataContext within DataTemplate

开发者 https://www.devze.com 2023-04-09 00:19 出处:网络
I\'m trying to bind MenuItem\'s Command to command contained in UserControl.DataContext. I\'ve found couple of similar question, but solution according to them is failing to me:

I'm trying to bind MenuItem's Command to command contained in UserControl.DataContext. I've found couple of similar question, but solution according to them is failing to me:

<UserControl ...>
<UserControl.Resources>
    <DataTemplate x:Key="TileItemStye">
        <Grid Width="100" Height="100">
            <Grid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Remove" 
                              Command="{Binding DataContext.RemoveItem, 
                              RelativeSource={RelativeSource FindAncestor,
                                             AncestorType=UserControl}}">
                    </MenuItem>
                </ContextMenu>
            </Grid.ContextMenu>
        </Grid>
    </DataTemplate>
</UserControl.Resources>
<Grid>
    <ListView ItemsSource="{Binding Path=Files}" 
              ItemTemplate="{DynamicResource TileItemStye}"  >
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelT开发者_开发问答emplate>
    </ListView.ItemsPanel>
</ListView>
</Grid>

UserControl's DataContext is ViewModel with ICommand RemoveItem and ObservableCollection<FileViewModel> Files.


If you are on .NET 4 there indeed is a more elegant solution:

<UserControl Name="uc" ...>
<!-- ... -->
    <MenuItem Header="Remove"
              Command="{Binding DataContext.RemoveItem,
                                Source={x:Reference uc}}"/>

(This requires that the template stays in the Resources, otherwise there will be a cyclical dependency error)


Menus are not drawn in the same Visual Tree as your Controls, which is why the RelativeSource binding does not work

You need to bind to the PlacementTarget of your ContextMenu to access the main Visual Tree

<MenuItem Header="Remove" 
          Command="{Binding PlacementTarget.DataContext.RemoveItem, 
              RelativeSource={RelativeSource FindAncestor, 
              AncestorType={x:Type ContextMenu}}}" />
0

精彩评论

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

关注公众号