【问题标题】:Databind a button click in a reusable Usercontrol数据绑定在可重用用户控件中单击的按钮
【发布时间】:2018-10-15 18:35:58
【问题描述】:

我正在使用 Mvvm/Prism 设计一个界面,我创建了一个用户控件,其背后的代码带有标签文本框按钮(没有 mvvm)

整个项目采用 mvvm 模式,我有一个主页,其中包含 3 个用户控件。

在我的用户控件中,我将标签内容数据绑定到属性(字符串)PROP1,文本框内容(字符串)PROP2 到属性(后面的代码),在我的 HOME 中,我只是将这些属性绑定到我的 HomeViewModel 中的属性

 <local:userControl  PROP1="{Binding Text}" PROP2="{Binding Name}" />

现在我想用相同的方法对按钮单击进行数据绑定,在我的 userControl 页面中要做的是

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

但我不知道如何将它存储在属性中,以便我以后可以使用它

这就是我想要的最终 Home 的样子

<local:userControl  Klick="{Binding Commandp}" PROP1="{Binding Textp}" PROP2="{Binding Namep}" />

和 HomeViewModel

class HomeViewModel : BindableBase
{
    public ICommand Commandp{ get; private set; }


    private readonly IRegionManager _regionManager;

    public HomeViewModel (IRegionManager regionManager)
    {
        Commandp= new DelegateCommand(() => NavigateTo("Docs"));
    }

    private void NavigateTo(string url)
    {
        _regionManager.RequestNavigate(Regions.Contentregoin, url);
    }
}

PS:我正在使用 ViewModelLocator.AutoWireViewModel

【问题讨论】:

    标签: c# wpf data-binding prism


    【解决方案1】:

    这与 PROP1PROP2 的工作方式相同 - 创建一个依赖属性,你就可以开始了。

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

    【讨论】:

      猜你喜欢
      • 2013-03-23
      • 1970-01-01
      • 2018-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多