我的usercontrol上有一个按钮
<Button Grid.Row="13" Grid.Column="7" Content="Save" Name="btnSave"
CommandParameter="{Binding CompanyDetails}"
Command="{Binding SaveCommand}" />
SaveCommand是在ViewModel中声明的RelayCommand。 CompanyDetails是同一ViewModel中的属性。 上面提到的ViewModel是我的UserControl的datacontext。
Public Class CompanyViewModel
Inherits ViewModelBase
Implements IDataErrorInfo
Private _myData As DataFromDatabase
Private _companyDetails As New CompanyDetailsBase
Private _saveCommand As RelayCommandWithParameter
Public Property CompanyDetails() As CompanyDetailsBase
Get
Return _companyDetails
End Get
Set(ByVal value As CompanyDetailsBase)
_companyDetails = value
OnPropertyChanged("CompanyDetails")
End Set
End Property
Public Property SaveCommand() As RelayCommandWithParameter
Get
If _saveCommand Is Nothing Then
Dim saveAction As New Action(Of Object)(AddressOf Me.SaveIt)
_saveCommand = New RelayCommandWithParameter(saveAction) ', Me.CanSave)
End If
Return _saveCommand
End Get
Set(ByVal value As RelayCommandWithParameter)
_saveCommand = value
End Set
End Property
Public Sub New()
_myData = New DataFromDatabase(My.Settings.ConnectionString)
_saveCommand = New RelayCommandWithParameter(New Action(Of Object)(AddressOf SaveIt))
End Sub
Public Function GetCompanyDetails(ByVal sap As String) As CompanyDetailsBase
CompanyDetails = _myData.GetCompanyDetails(sap)
Return CompanyDetails
End Function
Public Sub SaveIt(ByVal c As CompanyDetailsBase)
MessageBox.Show("Save customer " & c.Sap)
End Sub
End Class
usercontrol上的其他字段绑定到ObjectDataProvider,后者调用GetCompanyDetails函数。每次调用此函数时,CompanyDetails都会被设置,直到我调用SaveIt子例程。调用SaveIt时,其参数始终为Nothing。我在哪里弄错了? 非常感谢你的回答。
答案 0 :(得分:0)
在 CompanyViewModel 的构造中,使用 GetCompanyDetails 函数填充 CompanyDetails 。将构造函数更改为以下,
Public Sub New()
_myData = New DataFromDatabase(My.Settings.ConnectionString)
_saveCommand = New RelayCommandWithParameter(New Action(Of Object)(AddressOf SaveIt))
_companyDetails = GetCompanyDetails()
End Sub
这可能会有所帮助。 祝你好运。
答案 1 :(得分:0)
自从我做VB以来已经有一段时间了,我从来没有用WPF做过,但我想我知道你的问题是什么。
初始化Command的方式,实际上并没有传递参数。
当我在c#中执行此操作时,它看起来像=&gt;
_saveCommand = new RelayCommandWithParameter(
(param) =>
{
SaveIt((int)param);
},
// this line is the same as your commented out Me.CanSave
(param) => { return this.CanDisplaySelectedPolicy; });
所以你可以看到在lamda表达式中我传递了一个名为param的参数,然后将其放入SaveIt方法中。
当您创建新动作时,请尝试在其中放置一个lamda表达式,如上所示,因此您可以将参数传递给SaveIt方法。