首页 > 解决方案 > WPF命令参数如何使用

问题描述

我想拥有两种状态**(SmallPay,Credit)**,但这是由先前决定的UserControl(ItemDetail.xaml)

项目详细信息.xaml

<Border Background="#fb5106" CornerRadius="8" Cursor="Hand">
    <Border.InputBindings>
       <MouseBinding MouseAction="LeftClick" Command="{Binding Path=ClickPhoneNumberCommand}" CommandParameter="A"/>
    </Border.InputBindings>
    <TextBlock Text="SmallPay" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontSize="32" />
</Border>

<Border Grid.Column="2" Background="#e7001f" CornerRadius="8" Cursor="Hand">
    <Border.InputBindings>
        <MouseBinding MouseAction="LeftClick" Command="{Binding Path=ClickPhoneNumberCommand}" CommandParameter="B"/>
        </Border.InputBindings>
    <TextBlock Text="Credit" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White" FontSize="32" />
</Border>

视图模型.cs

public DelegateCommand ClickItemCommand
{
    get
    {
        return new DelegateCommand(delegate ()
        {
            SelectedPopupType = PopupTypes.ItemDetail;
                IsShowPopup = true;
        });
    }
}

public DelegateCommand ClickPhoneNumberCommand
{
    get
    {
        return new DelegateCommand(delegate ()
        {
            SelectedPopupType = PopupTypes.PhoneNumber;
            IsShowPopup = true;
        });
    }
}

然后我想commandParameter通过UserControl''打开ClickPhoneNumberCommand。但是,我不知道怎么做?有没有办法 no ViewModel

标签: c#wpfxaml

解决方案


您的代码为属性的每次返回返回一个委托。ClickItemCommand由于对象引用的工作方式,我认为这不适用于 WPF,我认为您应该使用字段来存储对 immutable 的单个引用Command,如下所示:

private readonly DelegateCommand clickItemCommand;

public MyViewModel()
{
    this.clickItemCommand = new DelegateCommand( this.OnItemClick );
}

private void OnItemClick(Object parameter)
{
    this.SelectedPopupType = PopupTypes.ItemDetail;
    this.IsShowPopup = true;
}

public DelegateCommand ClickItemCommand
{
    get { retrn this.clickItemCommand; }
}

推荐阅读