自定义控件工具栏需要在我的VM上调用方法。怎么做?

时间:2011-12-24 20:57:37

标签: c# silverlight xaml mvvm custom-controls

这是我的问题。我有UserControl包裹按钮组,它看起来像这样:(我显示2个按钮来说明它是什么)

<Button Content="Cancel"
        IsEnabled="{Binding State, Converter={StaticResource CancelEnabledConverter}}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <ei:CallMethodAction MethodName="Cancel" TargetObject="{Binding}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

<Button Content="Delete" 
        IsEnabled="{Binding State, Converter={StaticResource DeleteEnabledConverter}}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <ei:CallMethodAction MethodName="Delete" TargetObject="{Binding}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

现在,当我将此UserControl放在我的视图上时 - 按惯例,我会在我的VM上创建CancelDelete方法。因此,视图的XAML看起来很干净。

我想创建具有相同功能的自定义控件。在内部控制中,我将不得不处理按钮的onClick事件,并希望在VM上调用方法就像现在一样。我的代码看起来像什么?我想我需要以编程方式访问DataContext并以某种方式按名称调用方法。我设想像这样使用控件:

<myToolBar Mode="SaveExitDelete" />

所以,这将是好的和短暂的。但是myToolBar将显示3个按钮,这些按钮将在DataContext上调用3个方法(按惯例命名)。

任何指针?

修改

主要问题是如何使用programmaticaly BIND命令或方法来按钮。我理解命令如何工作,我正在使用PRISM,它有内置的DelegateCommand,我可以使用。当我知道方法名称或命令名称时,我不知道如何创建绑定程序。

以下是我的工作方式:

var button = new DitatToolbarButton(); button.Caption = "Cancel &\nExit"; button.Icon = new BitmapImage(new Uri("img_btn_cancel.png", UriKind.Relative)); button.Command = Binding("CancelCommand");

显然第3行是错的,但这就是我想要的。我希望能够硬编码包含我希望VM拥有的命令名称的字符串。

1 个答案:

答案 0 :(得分:0)

通常,这种事情可以使用命令完成。对于已经具有“Command”DependencyProperty的Button控件,它就像这样简单:

<Button Command="{Binding DoItCommand}">Do it</Button>

并在您的视图模型类中:

private ICommand DoItCommand
{
    get
    {
        return new DelegateCommand(param => DoIt(param), param => CanDoIt(param));
    }
}

其中DoIt()和CanDoIt()是视图模型中的方法,DelegateCommand的定义如下:

public class DelegateCommand : ICommand
{
    public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
    {
        // ...

这是here的一个很好的例子。在自定义控件上,您可以自己声明Command DependencyProperty。在没有Command DependencyProperty的框架控件上,您可以使用attached property

相关问题