我正在尝试使用自定义DependencyProperty为StackF中的堆栈面板制作鼠标(StackPanels不处理MouseEnter事件)。
我为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>
我的ViewModel看起来像这样:
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
更新
我能够获得编译和运行的代码,但是不会发生绑定。我似乎无法弄明白为什么。
答案 0 :(得分:1)
我相信这是你的问题:
DependencyProperty.RegisterAttached("MouseEnteredCommand",
GetType(ICommand),
GetType(MainWindowViewModel)
第一个GetType应该是属性的类型(这里你没关系)
第二个GetType shuold是包含类的类型,在你的情况下是“MouseEnterBehavior”
答案 1 :(得分:1)
您已将依赖项属性注册为MouseEnter ed 命令,但尝试绑定到MouseEnterCommand。
在旁注中,绑定不会使用您提供的Set调用设置DependencyProperty;它将直接调用SetValue。您需要将回调传递给RegisterAttached,以便您收到通知。