2012-12-05 146 views
3

我在Silverlight論壇上發佈了這個問題,但一直沒有能夠得到答案來解決我的問題,所以我希望大師在SO可以提供幫助!Silverlight:Parent ViewModel屬性值爲Child ViewModel屬性

基本上我在我的父viewmodel有一個實體屬性。當這個實體改變時,我需要在我的子視圖模型中的實體的ID。我用一個依賴屬性創建了一個子控件,並在構造函數中創建了一個綁定。我正在嘗試使用MVVM和MEF來實現所有這些。

我ParentViewModel:

[ExportPlugin(ViewModelTypes.ParentViewModel, PluginType.ViewModel)] 
[PartCreationPolicy(CreationPolicy.NonShared)] 
public class ParentViewModel: ViewModelBase 
{ 
    private Person _currentPerson; 
    public Person CurrentPerson 
    { 
     get { return _currentPerson; } 
     private set 
     { 
      if (!ReferenceEquals(_currentPerson, value)) 
      { 
       _currentPerson= value; 
       RaisePropertyChanged("CurrentPerson"); 
      } 
     } 
    } 
} 

我ParentUserControl:

<UserControl x:Class="MyApp.ParentUserControl" x:Name="ParentControl"> 
     <local:ChildUserControl PersonID="{Binding ElementName=ParentControl, Mode=TwoWay, Path=DataContext.CurrentPerson.ID}" /> 
</UserControl> 

我ChildUserControl代碼隱藏:

public partial class ChildUserControl : UserControl 
{ 
    #region Private Properties 
    private PluginCatalogService _catalogService = PluginCatalogService.Instance; 
    #endregion 

    #region Dependency Properties 
    public static readonly DependencyProperty PersonIDProperty = 
     DependencyProperty.Register("PersonID", typeof(int), typeof(ChildUserControl), new PropertyMetadata(OnPersonIDChanged)); 
    #endregion 

    #region Public Properties 
    public int PersonID 
    { 
     get { return (int)GetValue(PersonIDProperty); } 
     set { SetValue(PersonIDProperty, value); } 
    } 
    #endregion 

    #region Constructor 
    public ChildUserControl() 
    { 
     InitializeComponent(); 

     if (!ViewModelBase.IsInDesignModeStatic) 
      this.DataContext = _catalogService.FindPlugin(ViewModelTypes.ChildViewModel, PluginType.ViewModel); 

     this.SetBinding(PersonIDProperty, new Binding("PersonID") { Mode = BindingMode.TwoWay, Source = DataContext, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); 
    } 
    #endregion 

private static void OnPersonIDChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    ... 
} 

我ChildViewModel:

[ExportPlugin(ViewModelTypes.ChildViewModel, PluginType.ViewModel)] 
[PartCreationPolicy(CreationPolicy.NonShared)] 
public class ChildViewModel: ViewModelBase 
{ 
    private int _personID; 
    public int PersonID 
    { 
     get { return _personID; } 
     set 
     { 
      if (!ReferenceEquals(_personID, value)) 
      { 
       _personID= value; 
       RaisePropertyChanged("PersonID"); 
      } 
     } 
    } 
} 

我創建了OnPersonIDChanged事件以查看CurrentPerson實體是否更改,更改是在ChildControl中找到的,它是。它只是不被ChildControl ViewModel拾起。

任何幫助,非常感謝。

回答