Mvvm-Light 用户控制 RelayCommand TemplateBinding

Mvvm-Light User Control RelayCommand TemplateBinding

[UWP - Windows 10]

我是 MVVM-Light 的新手,所以我遇到了一些入门问题。我创建了一个名为 TileToolbar 的自定义用户控件,其中包含此 xaml:

  <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
    <RadioButton Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE141;" Foreground="Green"></RadioButton>
    <RadioButton Style="{StaticResource NavRadioButtonStyle}" Tag="&#xE7E6;" Foreground="Green"></RadioButton>
    <RadioButton Style="{StaticResource NavRadioButtonStyle}" Tag="&#xEB52;" Foreground="Green"></RadioButton>
</StackPanel>

现在我想为每个 RadioButton 添加一个 RelayCommand,我希望每个包含自定义用户控件的页面都能够绑定一个自定义 RelayCommand

所以我的问题是: 我如何在 UserControl 中创建类型为 RelayCommand 的 属性,例如 PinCommand,以便稍后可以在 xaml 中绑定到它,例如在 Mainpage 上?

So my question: How would I create a property like PinCommand of type RelayCommand in the UserControl so I can later bind to it in xaml for example on the Mainpage?

你可以在你的UserControl后面的代码中以RelayCommand的类型注册一个PinCommand,例如像这样:

public static DependencyProperty PinCommandProperty = DependencyProperty.Register("PinCommand", typeof(RelayCommand), typeof(TileToolbar), new PropertyMetadata(null));

public RelayCommand PinCommand
{
    get
    {
        return (RelayCommand)GetValue(PinCommandProperty);
    }
    set
    {
        SetValue(PinCommandProperty, value);
    }
}

现在您可以在您的 MainPage 中使用这个 TileToolbar 例如:

<Controls:TileToolbar Grid.Row="1" VerticalAlignment="Bottom" PinCommand="{Binding pinCommand, Mode=OneWay}" />

视图模型中的代码是这样的:

private RelayCommand _pinCommand;

public RelayCommand pinCommand
{
    get
    {
        if (_pinCommand == null)
        {
            _pinCommand = new RelayCommand(() =>
            {
                //TODO:
            },
            () => true);
        }
        return _pinCommand;
    }
}

为了将 RadioButtonCommand 连接到 TileToolBarPinCommand,您可以在用户控件中使用如下代码:

<RadioButton Tag="&#xEB52;" Foreground="Green" Command="{x:Bind PinCommand, Mode=OneWay}"></RadioButton>