例如,我有以下XAML:
<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按钮的引用:
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 (运行)而不是标签?
发布于 2022-02-25 08:15:50
ContextMenu是一个弹出窗口,这意味着它具有与其所有者不同的名称范围。因此,在这种情况下,ElementName将无法工作。正确的方法是使用ContextMune.PlacementTarget来引用所有者。
<MenuItem Command="ApplicationCommands.Copy"
CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>关于你得到的是Button而不是Label,我只是不能复制。通常,如果一个MenuItem不能解决它的CommandTarget,它应该被自动禁用。
https://stackoverflow.com/questions/71226560
复制相似问题