說,我有以下 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 號并將其放在標簽上。然后我嘗試使用標簽的背景關系選單復制標簽的文本(即此 ID)CommandTarget。但是,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(Run) 而不是標簽?
uj5u.com熱心網友回復:
ContextMenu是一個彈出視窗,這意味著它的名稱范圍與其所有者不同。所以ElementName在這種情況下是行不通的。正確的方法是使用ContextMune.PlacementTarget參考所有者。
<MenuItem Command="ApplicationCommands.Copy"
CommandTarget="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
而關于你得到Button而不是Label,我就是無法重現。通常,如果 aMenuItem不能解決它CommandTarget,它應該被自動禁用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436208.html
