我是MVVM和MVVM之光的新手,我来自vb.net背景。我已经设法创建了一些简单的学习项目,在一个视图中按钮不会调用命令。我有以下视图xaml(为了便于阅读而缩短):
<UserControl x:Class="FTC.View.NavigationView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:vm="clr-namespace:FTC_Application.FTC.ViewModel"
mc:Ignorable="d"
d:DesignWidth="900"
Height="161"
DataContext="{Binding NavigationView, Source={StaticResource Locator}}" >
<UserControl.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
</UserControl.Resources>
<Grid>
<Button HorizontalAlignment="Left" Margin="10" VerticalAlignment="Top"
Command="{Binding SwapParent}"
CommandParameter="{Binding Parent1}" Background="{x:Null}" BorderBrush="{x:Null}" Width="130" Height="45">
<TextBlock Text="{Binding Parent1}" Foreground="#FFE4E4E4"/>
</Button>
以下是viewmodel类中按钮函数
的代码Private _sNavs() As String = {"Dashboard", "Jobs", "People", "Products", "Financials", "Admin"}
Private _sParentNavs() As String
Public Property SwapParent As RelayCommand
Private Property ParentNavs() As String()
Get
Return _sParentNavs
End Get
Set(value As String())
If _CurrentParent = String.Empty Then
_CurrentParent = "Dashboard"
Else
If _sParentNavs.Contains(_CurrentParent) = False Then
Return
End If
End If
RefreshParents(_CurrentParent)
RaisePropertyChanged(ParentNavsPropertyName)
End Set
End Property
Public Sub New()
If _CurrentParent = String.Empty Then
_CurrentParent = "Dashboard"
End If
RefreshParents(_CurrentParent)
SwapParent = New RelayCommand(Sub()
ParentNavs = _sParentNavs
End Sub)
End Sub
Private Sub RefreshParents(sCurrent)
If _sNavs.Contains(sCurrent) = True Then
_sParentNavs = Filter(_sNavs, sCurrent, False, CompareMethod.Text)
Else
_sParentNavs = Filter(_sNavs, "Dashboard", False, CompareMethod.Text)
End If
Parent1 = _sParentNavs(0)
Parent2 = _sParentNavs(1)
Parent3 = _sParentNavs(2)
Parent4 = _sParentNavs(3)
Parent5 = _sParentNavs(4)
End Sub
因此,此代码旨在根据提供的值更改父数组,以包括除提供的值之外的所有项目。然后它将数组值分配给页面上的按钮。一切都按照按钮内容绑定工作,但由于某种原因命令没有触发。我在另一个视图模型上使用了这个精确的方法,它可以工作,
我需要一些帮助来了解为什么这不适用于此viewmodel
提前致谢
约旦国王答案 0 :(得分:0)
我改变了他定义命令对象的方式。
我重新处理了我的项目,不再使用上面的代码了,但他跟随的是在vb中使用lambdas定义命令对象的一些示例,其中addressof指的是类中的公共子/函数。
“Of String”接收一个string类型的命令参数到addressof命名的函数。第二个地址是一个返回布尔值的函数,它被命名为canexecute方法。
NavigateShellCommand = New RelayCommand(Of String)(AddressOf NavigateShell)
NavigateChildCommand = New RelayCommand(Of String)(AddressOf NavigateChild)
IsParentEnabled = New RelayCommand(Of String)(AddressOf NavigateChild, AddressOf ParentEnabled)
IsChildEnabled = New RelayCommand(Of String)(AddressOf NavigateChild, AddressOf ChildEnabled)
我希望这可以帮助某人,我花了一段时间才能真正理解它