2013-12-17 64 views
1

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

宣言子视图模型包括绑定不起作用:

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

宣言自定义控件:

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

子视图模型relivent代码:

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

我知道如何去做,但没有使用资源。这是当你设置你的控件DataContext ViewModel,然后做一个绑定relativesource。 :) –

+0

当然,这可以工作。我确实很喜欢将我的ViewModel声明为xaml资源的想法。如果我无法想出一个不同的解决方案,那可能是我会做的。 – CThin

+0

嗯,我实际上使用Caliburn.Micro库来连接我的ViewModels到控件而不是使用Resources。 TBH,除了在CollectionViewSource中使用它之外,我没有看到它的好处。 –

回答

0

任何约束力目标必须是依赖项属性 - 您无法绑定视图模型属性。一种替代的方法,根据您提出的东西,是对视图创建一个依赖属性,然后把它传递到视图模型那样:

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

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

((PagerViewModel)DataContext).PagesContent = DisplayedRawData 
相关问题