DataBinding到wpf中的上下文菜单?

时间:2012-06-04 13:26:56

标签: wpf xaml data-binding user-controls command

我有一个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>

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

我在这里错过了什么吗?

1 个答案:

答案 0 :(得分:0)

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

 <ContextMenu >
    <MenuItem Header="ITEM"
          Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type UserControl}}, Path=DataContext.DeleteCommand}">                          
    </MenuItem>
</ContextMenu>