【问题标题】:DataBinding to a context menu in wpf?DataBinding到wpf中的上下文菜单?
【发布时间】:2012-06-08 13:50:03
【问题描述】:

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

我错过了什么吗?

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • 你在哪里分配DataContext?您可能对分配 DataContext 的方式有疑问。采取look at the Output Window 并分享任何数据绑定错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多