雖然迦勒的答案是正確的,它不包括工作代碼。我安裝了一個使用VB.NET的例子(對不起),所以我在這裏發佈它。
<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:AttachedBehaviorTest.AttachedBehaviorTest"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel>
<TextBlock local:ContextMenuLeftClickBehavior.IsLeftClickEnabled="True">Some Text Goes Here
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Test1" />
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</StackPanel>
</Grid>
</Window>
Namespace AttachedBehaviorTest
Public NotInheritable Class ContextMenuLeftClickBehavior
Private Sub New()
End Sub
Public Shared Function GetIsLeftClickEnabled(obj As DependencyObject) As Boolean
Return CBool(obj.GetValue(IsLeftClickEnabled))
End Function
Public Shared Sub SetIsLeftClickEnabled(obj As DependencyObject, value As Boolean)
obj.SetValue(IsLeftClickEnabled, value)
End Sub
Public Shared ReadOnly IsLeftClickEnabled As DependencyProperty = _
DependencyProperty.RegisterAttached("IsLeftClickEnabled", GetType(Boolean), GetType(ContextMenuLeftClickBehavior), New UIPropertyMetadata(False, AddressOf OnIsLeftClickEnabled))
Private Shared Sub OnIsLeftClickEnabled(sender As Object, e As DependencyPropertyChangedEventArgs)
Dim fe As FrameworkElement = TryCast(sender, FrameworkElement)
If fe IsNot Nothing Then
Dim IsEnabled As Boolean = CBool(e.NewValue)
If IsEnabled = True Then
AddHandler fe.MouseLeftButtonUp, AddressOf OnMouseLeftButtonUp
Debug.Print("Added Handlers")
Else
RemoveHandler fe.MouseLeftButtonUp, AddressOf OnMouseLeftButtonUp
Debug.Print("RemovedHandlers")
End If
End If
End Sub
Private Shared Sub OnMouseLeftButtonUp(sender As Object, e As RoutedEventArgs)
Debug.Print("OnMouseLeftButtonUp")
Dim fe As FrameworkElement = TryCast(sender, FrameworkElement)
If fe IsNot Nothing Then
'Next Line is Needed if Context Menu items are Data Bound
'fe.ContextMenu.DataContext = fe.DataContext
fe.ContextMenu.IsOpen = True
End If
End Sub
End Class
End Namespace
來源
2014-03-26 15:57:32
HK1
這是一個偏離Windows的標準,你是否有很好的理由這樣做? – 2009-02-17 08:43:36
這是一個好點,也許我應該ld正在使用ContextMenu以外的其他功能來完成此操作。它基本上是一個下拉式菜單,當你點擊該項目時,不是按鈕,而是一種緊張的方式。ContextMenu似乎是一個明顯的選擇,但也許這是錯誤的。 – timothymcgrath 2009-02-20 03:39:51
看到我在這裏使用Expression Blend觸發器的答案:http://stackoverflow.com/a/4917707/87912 – 2012-08-21 04:57:13