我们希望定义一些按钮在每个页面上对一组用户可见。我们将按钮定义为 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/