2010-01-11 73 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的定义)我无法真正说出这是什么原因。

相关问题