[英]How to bind application commands to view model(WPF)?
我已經閱讀了Josh Smiths關於使用RelayCommand查看模型的綁定命令的文章。 但是,我需要將ApplicationCommands.Save綁定到視圖模型,以便當用戶單擊保存菜單項時,它將在窗口中處理。 這怎么可能?
有一個很好的教程可以幫助綁定應用程序命令。
public CommandBindingCollection CommandBindings { get; } public YourViewModel() { //Create a command binding for the save command var saveBinding = new CommandBinding(ApplicationCommands.Save, SaveExecuted, SaveCanExecute); //Register the binding to the class CommandManager.RegisterClassCommandBinding(typeof(YourViewModel), saveBinding); //Adds the binding to the CommandBindingCollection CommandBindings.Add(saveBinding); }
設置附加屬性。 閱讀有關如何做到這一點的文章 。
然后使用附加屬性綁定到它。
<UserControl local:AttachedProperties.RegisterCommandBindings="{Binding CommandBindings}"> <Window.DataContext> <local:YourViewModel></local:YourViewModel> </Window.DataContext> </UserControl>
我知道我們使用服務的最佳解決方案。 例如,像這樣的ICommandBindingsProvider:
public interface ICommandBindingsProvider
{
CommandBindingCollection CommandBindings { get; }
}
這會被注入您的ViewModel並像這樣使用:
public MyViewModel(ICommandBindingsProvider commandBindings)
{
commandBindings.Add(new CommandBinding(....));
}
如何注入服務將取決於您正在使用的MVVM框架。 大多數(但不是全部)支持某種服務注入功能。 如果您需要一個更具體的代碼示例,請查看Onyx ,它執行服務注入並具有執行此操作的服務。
你的保存菜單項是如何創建的? 它某處必須綁定到ApplicationCommands.Save? 您可以更改它,以便它與ViewModel的保存綁定。
或者,將save命令綁定放在viewmodel上,然后將數據綁定到它,類似於(偽代碼)
在viewmodel中:
...
public Command SaveCommand { get { return yourCodeHere; } }
...
在視圖中:
<Button Command="{Binding Path=SaveCommand}" Content="Click"/>
更新:我剛剛嘗試綁定到命令綁定中的命令,但它不起作用。 我在想的是綁定命令 。
首先在ViewModels上定義一個CommandBindings屬性(與Views相同的定義)。
然后,對於ViewModel實現的每個Command,將CommandBinding添加到ViewModel的CommandBindings。
然后,當你設置:
view.DataSource = viewModel;
還設置:
view.CommandBindings.AddRange(viewModel.CommandBindings);
我想可以使用CommandBindings屬性的綁定來完成(無法確定)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.