简体   繁体   English

在基本视图模型中定义命令

[英]Defining command in base View model

We would like define some button be visible in every page for a set of users.我们希望为一组用户在每个页面中定义一些可见的按钮。 We defined button as control template for view and called out it in the pages that require them to be displayed.我们将按钮定义为视图的控件模板,并在需要显示它们的页面中调用它。

<Button ImageSource="home_footer.png" BackgroundColor="Transparent" HorizontalOptions="FillAndExpand" 
        Command="{TemplateBinding BindingContext.HomeCommand}"/>

Here command is selected according to the binding context, ie corresponding view model.这里的命令是根据绑定上下文选择的,即对应的视图模型。 Command need to written multiple times.命令需要多次写入。 I thought of including the command in base view model so that it needs to written only once.我想在基本视图模型中包含该命令,以便它只需要编写一次。 Is there any option for implementing this option.是否有任何选项可以实现此选项。 Thanks in advance.提前致谢。

In your BaseViewModel add a command在你的 BaseViewModel 添加一个命令

    public ICommand HomeCommand { get; set; }

In your base ContentPage add a bindable property that supplies you this command:在您的基本ContentPage添加一个可绑定属性,为您提供以下命令:

   public ICommand Command
    {
        get => (ICommand)GetValue(CommandProperty);
        set => SetValue(CommandProperty, value);
    }

    public object CommandParameter
    {
        get => GetValue(CommandParameterProperty);
        set => SetValue(CommandParameterProperty, value);
    }


    public static readonly BindableProperty CommandProperty = BindableProperty.Create(
        nameof(Command),
        typeof(ICommand),
        typeof(ClassName),
        null
        );

    public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create(
        nameof(CommandParameter),
        typeof(object),
        typeof(ClassName),
        null
        );

Supply a command to this property from the ContentPage从 ContentPage 向该属性提供命令

<base:CustomContentPage ....
Command="{Binding HomeCommand}">

Set it to your Button something like:将其设置为您的按钮,例如:

You can give it a better name to explain the behaviour,你可以给它一个更好的名字来解释这种行为,

Goodluck!祝你好运!

Feel free to get back if you have queries!如果您有任何疑问,请随时回来!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM