首页 > 解决方案 > 在可重用的用户控件中使用传递参数的数据绑定属性

问题描述

我有一个包含按钮和文本框的用户控件,我在页面中使用了 3 次用户控件具有代码隐藏,但其余项目采用 Mvvm 模式。

在我的用户控制中,我将按钮单击数据绑定到属性 Klick

public static readonly DependencyProperty KlickProperty = DependencyProperty.Register( nameof(Klick), typeof(ICommand), typeof(userControl), new PropertyMetadata( default(ICommand) ) );

public ICommand Klick
{
    get { return (ICommand)GetValue( KlickProperty ); }
    set { SetValue( KlickProperty, value ); }
}

在用户控件 xaml 上:

<Button Content="Button" Command="{Binding Klick}"/>

现在在我的 PageView 中我使用 3 个控件:

<local:userControl Klick="{Binding NavigateToMain}"/>
<local:userControl Klick="{Binding NavigateToMain}"/>
<local:userControl Klick="{Binding NavigateToMain}"/>

我想要做的是能够通过绑定传递一个字符串,这样我就可以知道点击了什么按钮(什么用户控件)之类的

Command="{Binding NavigateToMain}" CommandParameter="Button_from_usercontrol _1"

这是其余的代码

class PageViewModel : BindableBase
{
    public ICommand NavigateToMain{ get; private set; }

    private readonly IRegionManager _regionManager;

public PageViewModel(IRegionManager regionManager)
{
    _regionManager = regionManager;
   NavigateToMain = new DelegateCommand(() => NavigateTo());
}


    private void NavigateTo()
    {
        _regionManager.RequestNavigate(Contentregionn, Main);
    }
}

标签: c#wpfmvvmdata-bindingprism

解决方案


这很可能会作为重复项关闭...在此之前,它的工作方式PROP1PROP2and相同Klick- 创建一个依赖属性,你就可以开始了。

public static readonly DependencyProperty KlickParameterProperty = DependencyProperty.Register( nameof(KlickParameter), typeof(object), typeof(userControl), new PropertyMetadata( default(object) ) );

public object KlickParameter
{
    get { return GetValue( KlickParameterProperty ); }
    set { SetValue( KlickParameterProperty, value ); }
}

推荐阅读