1

我有一个UserControl, 定义如下:

<UserControl x:Name=userControlName>   
    <UserControl.Resources>      
        <Style TargetType="{x:Type MyControl}">
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu >
                        <MenuItem Header="ITEM"
                                  Command="{Binding ElementName=userControlName, Path=DeleteCommand">                          
                        </MenuItem>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type controlType}">                        
                        <Grid>                            
                            <!--MyContentHere-->
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>        
        </Style>     
    </UserControl.Resources>

    <Grid>
       <!--Content -->
       <ListBox>
        <ListBoxItem> <!--is of Type MyControl-->
       </ListBox>
    </Grid>
</UserControl>

这不起作用,因为DataContext未找到 userControlName。

我在这里错过了什么吗?

4

1 回答 1

0

您应该尝试使用RelativeSource这样的 WPF 绑定:

 <ContextMenu >
    <MenuItem Header="ITEM"
          Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.DeleteCommand}">                          
    </MenuItem>
</ContextMenu>
于 2012-06-04T13:41:18.480 回答