我想使用自定义DependencyProperty(StackPanels不处理MouseEnter事件)在WPF中的堆栈面板的鼠标。将自定义DependencyProperty附加到WPF中的StackPanel?
我创建了一个类中的DependencyProperty像这样:
Public Class MouseEnterBehavior
Public Shared Property MouseEnterProperty As DependencyProperty =
DependencyProperty.RegisterAttached("MouseEnter",
GetType(ICommand),
GetType(MouseEnterBehavior),
New PropertyMetadata(Nothing, AddressOf MouseEnterChanged))
Public Shared Function GetMouseEnter(ByVal obj As DependencyObject) As ICommand
Return CType(obj.GetValue(MouseEnterProperty), ICommand)
End Function
Public Shared Sub SetMouseEnter(ByVal obj As DependencyObject, ByVal value As ICommand)
obj.SetValue(MouseEnterProperty, value)
End Sub
Public Shared Sub MouseEnterChanged(ByVal obj As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
Dim element As UIElement = TryCast(obj, UIElement)
If element IsNot Nothing Then
AddHandler element.MouseEnter, AddressOf uiElement_MouseEnter
End If
End Sub
Public Shared Sub uiElement_MouseEnter(ByVal sender As Object, ByVal e As EventArgs)
Dim uiElement As UIElement = TryCast(sender, UIElement)
Dim command As ICommand = GetMouseEnter(uiElement)
If command IsNot Nothing And command.CanExecute(uiElement) Then
command.Execute(uiElement)
End If
End Sub
End Class
我的视图看起来是这样的:
<Window x:Class="MainWindowView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel Height="76" vm:MouseEnterBehavior.MouseEnterCommand="{Binding MouseEnteredCommand}" HorizontalAlignment="Left" Margin="212,117,0,0" VerticalAlignment="Top" Width="88" Background="#72000000" />
</Grid>
</Window>
我的视图模型是这样的:
Public Class MainWindowViewModel
Inherits ViewModelBase
Implements INotifyPropertyChanged
Private cmdMouseCommand As RelayCommand
Public ReadOnly Property MouseEnteredCommand As ICommand
Get
If cmdMouseCommand Is Nothing Then
cmdMouseCommand = New RelayCommand(AddressOf OnMouseEnterCommand)
End If
Return cmdMouseCommand
End Get
End Property
Private Sub OnMouseEnterCommand(ByVal obj As Object)
''//Do something
End Sub
End Class
更新
我能够获得编译和运行的代码,但不会发生绑定。我似乎无法弄清楚为什么。
非常感谢您的帮助。我想我已经开始明白这是如何运作的更好一点。我对上面的代码做了一些修改,显示了我为DP设置回调的尝试。但是,命令绑定似乎不会发生。我在每种方法上都加入了断点,并且没有一个被击中。任何想法我做错了什么? – Daniel 2010-07-08 18:31:51