【问题标题】:Passing parameters to Custom control ViewModel, MVVM将参数传递给自定义控件 ViewModel、MVVM
【发布时间】:2013-12-17 21:37:05
【问题描述】:

我在视图中声明了一个自定义控件。控件有自己的 ViewModel,我在父视图的 XAML 中声明它。我想通过绑定将一个值传递给这个子 ViewModel,但我没有使用依赖属性,也不想使用。有没有办法解决这个问题?还是我需要大量返工?

子 ViewModel 的声明,包括不起作用的绑定:

<Window.Resources>
    <uc:PagerViewModel x:Key="PagerDataContext" PagesContent="{Binding DisplayedRawData}">
    </uc:PagerViewModel>
<Window.Resources>

自定义控件声明:

   <uc:Pager Grid.Row="1" DataContext="{StaticResource PagerDataContext }"/>

子 ViewModel 重新激活代码:

    public string PagesContent
    {
        get
        {
            return _pagesContent;
        }
        set
        {
            _pagesContent = value;
            OnPropertyChanged("PagesContent");
        }
    }
    private string _pagesContent = string.Empty;

【问题讨论】:

  • 我知道怎么做,但不知道资源。当你设置你的控件 DataContext ViewModel 然后做一个 Binding relativesource。 :)
  • 当然可以。我真的很喜欢将我的 ViewModels 声明为 xaml 资源的想法。如果我无法想出不同的解决方案,我可能会这样做。
  • 好吧,我实际上会使用 Caliburn.Micro 库将我的 ViewModel 连接到控件,而不是使用资源。 TBH,除了与 CollectionViewSource 一起使用之外,我看不到它的好处。

标签: wpf xaml mvvm custom-controls viewmodel


【解决方案1】:

任何绑定目标都必须是依赖属性——您不能将 绑定到 视图模型属性。根据您提供的内容,另一种方法是在 view 上创建一个依赖属性,然后以这种方式将其传递给 view-model:

<Window.Resources>
    <uc:PagerViewModel x:Key="PagerDataContext" />
<Window.Resources>

所以,在uc:Pager控件中声明依赖属性DisplayedRawData;在其PropertyChangedEventHandler 中,将新值传递给视图模型:

((PagerViewModel)DataContext).PagesContent = DisplayedRawData

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-27
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多