我想在我的类CommandProvider中实现CommandParameter,该类用于命令(Button等)并从ICommand继承,但是我不知道如何实现。例子:
XAML
<TreeViewItem Header="Playlist" ItemsSource="{Binding ItemSourceTree}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding Path=NewPlaylist}"
CommandParameter="{Binding Path=NamePlaylist}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<TreeViewItem.ItemTemplate>
<DataTemplate DataType="{x:Type local:PlaylistDB}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=NamePlaylist}">
</TextBlock>
</StackPanel>
</DataTemplate>
</TreeViewItem.ItemTemplate>
</TreeViewItem>
控制台说,找不到NamePlaylist。
并将一个函数链接到Binding
NewPlaylist
:public ICommand NewPlaylist { get { return new CommandProvider((obj) => DoubleClickTest(obj)); } }
函数
public void DoubleClickTest(object obj)
{
var tmp = obj as string;
Console.WriteLine(tmp);
}
所以我需要修改我的类CommandProvider来接受参数吗?我该怎么做?
命令提供者
public class CommandProvider : ICommand
{
#region Constructors
public CommandProvider(Action<object> execute) : this(execute, null) { }
public CommandProvider(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
播放列表数据库
public class PlaylistDB
{
public string NamePlaylist { get; set; }
}
我想在函数
NamePlaylist
中检索DoubleClickTest()
,并希望在CommandParameter
中传递它。我怎样才能做到这一点? 最佳答案
使用下面的类接受commandparameters
使用ICommand
,
public class DelegateCommand: ICommand
{
#region Constructors
public DelegateCommand(Action<object> execute)
: this(execute, null) { }
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
用法:
public ICommand CloseCommand
{
get
{
return new DelegateCommand((obj)=>CloseMethod(obj));
}
}
obj
是在上面的示例中传递的command parameter
。关于c# - CommandParameter如何在MVVM中工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34272982/