我一直在這個問題上停留了幾個小時。我正在嘗試在WPF中實現MVVM樣式的Word加載項。我沒有使用MVVM工具包。我有一個停靠在WinForm中的WPF用戶控件。雖然我能夠在獲勝窗體中看到WPF用戶控件並與其交互,但當我單擊該按鈕時,綁定到WPF按鈕的通用RelayCommand將不會執行。 RelayCommand位於ViewModel.cs中,視圖的DataContext通過代碼隱藏進行設置。我確定我在做一些愚蠢的事情,但無法弄清楚它是什麼,因此不確定爲什麼RelayCommand屬性的get {}不會被執行。請參閱下面的代碼。先謝謝您的幫助!RelayCommand不會在按鈕上執行單擊
RelayCommand.cs(代碼段不包括命名空間,並且包括語句)
/// <summary>
/// RelayCommand
/// </summary>
/// <typeparam name="T">Generic Parameter</typeparam>
public class RelayCommand<T> : ICommand where T : class
{
#region Constructors
/// <summary>
/// RelayCommand constructor
/// </summary>
/// <param name="exec">Delegate that encapsulates a method that takes in a single parameter and returns void</param>
/// <param name="canExec">Delegate that encapsulates a method that defines a set of criteria and returns a true if criteria is met; else false</param>
public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
{
if (execute == null)
throw new ArgumentNullException("execute is null");
_canExecute = canExecute;
_execute = execute;
}
#endregion
#region Members
/// <summary>
/// Execute method
/// </summary>
/// <param name="param">Parameter</param>
public void Execute(object param)
{
T obj = param as T;
if(obj != null)
{
_execute(obj);
}
}
/// <summary>
/// CanExec is a method that shows whether or not execution can happen
/// </summary>
/// <param name="param">Parameter</param>
/// <returns>true if can execute; else false</returns>
public bool CanExecute(object param)
{
if (_canExecute == null)
return true;
T obj = param as T;
return obj == null || _canExecute(obj);
}
/// <summary>
/// CanExec event changed
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
#region Fields
private readonly Predicate<T> _canExecute;
private readonly Action<T> _execute;
#endregion
}
SubmissionUserControl.xaml(僅有相關的代碼段。排除一些代碼)
<Button Grid.Column="2" x:Name="SubmitButton" Command="{Binding Path=SubmitCommentCommand}"
Content="Submit" HorizontalAlignment="Right" Margin="5"/>
SubmissionUserControl。 xaml.cs(包含我參考ViewModel的片段)
ViewModel viewModel;
public SubmissionUserControl()
{
InitializeComponent();
viewModel = new ViewModel();
DataContext = viewModel;
}
ViewModel.cs(不包括一些代碼。只顯示相關RelayCommand)
/// <summary>
/// SubmitCommentCommand responsible for interacting with UI to submit a comment.
/// </summary>
/// <returns>Returns a RelayCommand that executes a method to Save comments from the comment box</returns>
public ICommand SubmitCommentCommand
{
get
{
return _submitCommentCommand ?? (_submitCommentCommand = new RelayCommand<object>(param => this.SaveComment()));
}
}
您的代碼沒有錯..檢查Datacontext應用正確..添加另一個文本屬性,並將其綁定到文本塊,並檢查顯示? – Sankarann
使用Snoop(http://snoopwpf.codeplex.com/)在運行時檢查您的datacontext – blindmeis
在我看來,您不發送命令參數,並且在您的RelayCommand實現中,出於某種原因,只有在參數isn 't null。 –