c# - 在基本 View 模型中定义命令

标签 c# xamarin xamarin.forms

我们希望定义一些按钮在每个页面上对一组用户可见。我们将按钮定义为 View 的控制模板,并在需要显示按钮的页面中调用它。

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

这里的命令是根据绑定(bind)上下文(即相应的 View 模型)来选择的。命令需要多次写入。我考虑将该命令包含在基本 View 模型中,以便只需要编写一次。是否有任何选项可以实现此选项。 提前致谢。

最佳答案

在你的 BaseViewModel 中添加一个命令

    public ICommand HomeCommand { get; set; }

在您的基本 ContentPage 中添加一个可绑定(bind)属性,为您提供此命令:

   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
        );

从 ContentPage 向此属性提供命令

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

将其设置为您的按钮,例如:

您可以给它一个更好的名称来解释该行为,

祝你好运!

如果您有疑问,请随时回复!

关于c# - 在基本 View 模型中定义命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60316830/

相关文章:

c# - 泛型类型的转换无效

c# - Xamarin.Forms:独立于平台的应用程序菜单

c# - 解除分配对象后,.NET Core 应用进程内存不会减少

c# - 如何从二进制 (C#) 模块调用 PowerShell Cmdlet?

ios - 使用 LaunchImages 和 LaunchScreen 的区别

ios - 显示 Root View Controller 后黑屏,仅在继承 PayPalPaymentDelegate 时

c# - 我的 session 状态序列化有问题

c# - 如何从现有的 excel 文件中读取单元格值

c# - 如何在自定义选择器中设置和获取选定值?该值不可更改

image - Xamarin Forms - 使用模态弹出窗口时相机和图像选择器不起作用