[英]Command to call method from viewmodel
好吧,我傾向於避免使用命令,因為他們總是設法混淆我的地獄,但我正在一個新的項目,我正在嘗試正確地構建它,我的視圖背后沒有代碼。 基本上我現在正試圖做的就是連接一個按鈕,它觸發一個命令,在我的視圖模型上做一些事情,不知怎么這么簡單仍然給我帶來麻煩。 我想我很接近但不能完全到達那里。 這就是我現在所擁有的。
<Window.Resources>
<RoutedUICommand x:Key="GetMusic" />
</Window.Resources>
<Window.DataContext>
<core:ViewMain />
</Window.DataContext>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource GetMusic}" Executed="GetMusicExecuted"/>
</Window.CommandBindings>
視圖模型現在幾乎沒什么
public class ViewMain
{
public MusicCollection Music { get; set; }
private void GetMusicExecuted(object sender, ExecutedRoutedEventArgs e)
{
//Logic
}
}
現在我要做的是連接我在命令綁定中設置的命令,只是在我的視圖模型中調用我執行的方法,但它試圖在視圖本身中找到該方法。 有沒有辦法可以將它引導到我的視圖模型中的方法,或者更好的方法來設置它來完成同樣的事情? 希望一開始就保持簡單,所以我不會太早打擾我的想法。
我傾向於使用自己的命令類,實現ICommand。 然后我將Button Command屬性綁定到視圖模型中的command屬性。 單擊該按鈕時,它將執行任何綁定到Command屬性的Execute方法。
這是丑陋的兩分鍾版本,但它顯示了如何創建一個Command類,然后為它指定委托,指向您在視圖模型上喜歡的任何方法。
ViewModel:
public class MyViewModel
{
public MyCommand ActionCommand
{
get;
set;
}
public MyViewModel()
{
ActionCommand = new MyCommand();
ActionCommand.CanExecuteFunc = obj => true;
ActionCommand.ExecuteFunc = MyActionFunc;
}
public void MyActionFunc(object parameter)
{
// Do stuff here
}
}
public class MyCommand : ICommand
{
public Predicate<object> CanExecuteFunc
{
get;
set;
}
public Action<object> ExecuteFunc
{
get;
set;
}
public bool CanExecute(object parameter)
{
return CanExecuteFunc(parameter);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
ExecuteFunc(parameter);
}
}
View會這樣綁定它(假設DataContext設置為視圖模型的一個實例):
<Window x:Class="exp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Command="{Binding Path=ActionCommand}">Action</Button>
</Grid>
</Window>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.