2010-01-11 72 views
1

我正在使用viewmodel模式,所以我的自定義用戶控件的DataContext實際上是真實數據的視圖模型包裝。如何在不清除依賴屬性的情況下設置DataContext?

我的自定義控件可以包含自定義控件的分層實例。

我在自定義控件中爲真實數據創建了一個DependencyProperty,並希望在通過綁定設置數據時爲其創建新的視圖模型,然後將用戶控件的datacontext設置爲新的viewmodel。但是,似乎設置DataContext屬性會導致我的真實數據DependencyProperty無效並設置爲空。任何人都知道解決這個問題的方法,或者更確切地說,我應該使用viewmodels?

用戶控件:

public partial class ArchetypeControl : UserControl 
{ 
    public static readonly DependencyProperty ArchetypeProperty = DependencyProperty.Register(
     "Archetype", 
     typeof(Archetype), 
     typeof(ArchetypeControl), 
     new PropertyMetadata(null, OnArchetypeChanged) 
    ); 

    ArchetypeViewModel _viewModel; 

    public Archetype Archetype 
    { 
     get { return (Archetype)GetValue(ArchetypeProperty); } 
     set { SetValue(ArchetypeProperty, value); } 
    } 

    private void InitFromArchetype(Archetype newArchetype) 
    { 
     if (_viewModel != null) 
     { 
      _viewModel.Destroy(); 
      _viewModel = null; 
     } 

     if (newArchetype != null) 
     { 
      _viewModel = new ArchetypeViewModel(newArchetype); 

      // calling this results in OnArchetypeChanged getting called again 
      // with new value of null! 
      DataContext = _viewModel; 
     } 
    } 

    // the first time this is called, its with a good NewValue. 
    // the second time (after setting DataContext), NewValue is null. 
    static void OnArchetypeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) 
    { 
     var control = (ArchetypeControl)obj; 

     control.InitFromArchetype(args.NewValue as Archetype); 
    } 
} 

視圖模型:

class ArchetypeComplexPropertyViewModel : ArchetypePropertyViewModel 
{ 
    public Archetype Value { get { return Property.ArchetypeValue; } } 
} 

的XAML:

<Style TargetType="{x:Type TreeViewItem}"> 
     <Style.Triggers> 
      <DataTrigger Binding="{Binding ViewModelType}" Value="{x:Type c:ArchetypeComplexPropertyViewModel}"> 
       <Setter Property="Template" Value="{StaticResource ComplexPropertyTemplate}" /> 
      </DataTrigger> 
     </Style.Triggers> 
    </Style> 

<ControlTemplate x:Key="ComplexPropertyTemplate" TargetType="{x:Type TreeViewItem}"> 
     <Grid> 
      <c:ArchetypeControl Archetype="{Binding Value}" /> 
     </Grid> 
    </ControlTemplate> 

修剪的什麼,我試圖做樣本在這個問題中提到了這個問題的Cannot databind DependencyProperty評論,但從未得到解決

+0

從外部混合綁定集(從而隱式使用DataContext),並設置新的DataContext不起作用,正如您發現的那樣。另見http://stackoverflow.com/questions/25672037/how-to-correctly-bind-to-a-dependency-property-of-a-usercontrol-in-a-mvvm-framew – 2016-07-19 09:30:50

回答

1

通過這樣做:

<c:ArchetypeControl Archetype="{Binding Value}" /> 

您結合您的Archetype財產上的數據上下文稱爲Value財產。通過將數據上下文更改爲新的ArchetypeViewModel,可以有效地對綁定進行新的評估。您需要確保新的ArchetypeViewModel對象具有非空Value屬性。

沒有看到更多的代碼(具體來說,ArchetypeComplexPropertyViewModelArchetypePropertyViewModel的定義)我無法真正說出這是什麼原因。

相關問題