首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在WPF中获得CommandTarget

无法在WPF中获得CommandTarget
EN

Stack Overflow用户
提问于 2022-02-22 18:30:44
回答 1查看 84关注 0票数 0

例如,我有以下XAML:

代码语言:javascript
复制
<r:RibbonWindow x:Class="WPFApp.Root"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:r="urn:fluent-ribbon"
        xmlns:local="clr-namespace:WPFApp"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="FL Query" Height="450" Width="800">

  <Window.CommandBindings>
    <CommandBinding Command="ApplicationCommands.Copy" Executed="OnCopy"/>
  </Window.CommandBindings>
  
  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition Height="Auto"/>
      <RowDefinition/>
    </Grid.RowDefinitions>

    <r:Ribbon Grid.Row="0">

      <r:RibbonTabItem Header="Home">
        <r:RibbonGroupBox Header="ID">
          <r:TextBox x:Name="txtID" Header="ID:" Width="100"/>
          <r:Button Size="Large"
                    LargeIcon="pack://application:,,,/WPFApp;component/img/Run.png" 
                    Click="OnAction">
                    Content="Run"/>
        </r:RibbonGroupBox>
      </r:RibbonTabItem>

    </r:Ribbon>

    <Grid Grid.Row="1">
      <Label x:Name="lbl">
        <Label.ContextMenu>
          <ContextMenu>
            <MenuItem Command="ApplicationCommands.Copy"
                      CommandTarget="{Binding ElementName=lbl}"/>
          </ContextMenu>
        </Label.ContextMenu>
      </Label>
    </Grid>

  </Grid>
</r:RibbonWindow>

Run按钮后,我从数据库中检索ID号,并将其放入标签中。然后,我尝试使用CommandTarget复制label的文本(即这个ID)和label的上下文菜单。但是,e.Source保留对以前按下的Run按钮的引用:

代码语言:javascript
复制
private void OnCopy(object sender, ExecutedRoutedEventArgs e)
{
  // sender = WPFApp.Root
  // e.Source = Fluent.Ribbon
  // e.OriginalSource = class "Fluent.Button": Header = "Run", Size = Large, IsSimplified = false
    
  // label is NULL here
  var label = e.Source as Label;
  Clipboard.SetText(label.Content.ToString());
}

为什么CommandTarget不能工作?为什么我要得到Button (运行)而不是标签?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-25 08:15:50

ContextMenu是一个弹出窗口,这意味着它具有与其所有者不同的名称范围。因此,在这种情况下,ElementName将无法工作。正确的方法是使用ContextMune.PlacementTarget来引用所有者。

代码语言:javascript
复制
<MenuItem Command="ApplicationCommands.Copy"
          CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>

关于你得到的是Button而不是Label,我只是不能复制。通常,如果一个MenuItem不能解决它的CommandTarget,它应该被自动禁用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71226560

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档