2014-02-06 32 views
3

目標是直接訪問子ViewModel中的屬性,而不會丟失整個ViewModel結構的上下文。我怎樣才能直接綁定到兒童viewmodel?

當前,我有一個字典中的資源,該字典保存對ViewModel的引用,該引用用作整個應用程序的數據上下文。

所以,我對每個視圖的DataContext看起來是這樣的:

DataContext="{StaticResource mainViewModel}" 

在我的ViewModel我有嵌套子的ViewModels像這樣:

public class ParentViewModel { 
    public ChildVM ChildVM { get; set; } 
    public ParentVM(){ 
     ChildVM = new ChildViewModel(); 
    } 
} 

public class ChildViewModel { 
    public string SomeProperty { get; set; } 
} 

在我看來,我可以從訪問屬性數據上下文像這樣:

<Button Text="{Binding ChildVM.SomeProperty}"/> 

但是這變得非常重複。我希望能夠做到:

<Button Text="{Binding SomeProperty}"/> 

用我的DataContext設置爲這樣的僞:

DataContext="{StaticResource MainViewModel, Path=ParentVM.ChildVM}" 

任何想法?

回答

4

您可以更改DataContext爲控制

<!-- DataContext is ParentViewModel --> 
<Grid> 
    <!-- change DataContext to ChildViewModel --> 
    <Grid DataContext="{Binding Path=ChildVM}"> 
     <Button Content="{Binding SomeProperty}"/> 
     <Button Content="{Binding AnotherChildProperty}"/> 
    </Grid> 
</Grid> 
+0

這是偉大的,如果你只打算使用一個子視圖模型上只說自己的用戶控件的一部分,但我認爲Alberto的回答更清楚地涵蓋了整個UserControl。 雖然我必須牢記這一點。 – jporcenaluk

+0

雖然它不像Alberto的答案那麼幹淨,但子視圖模型仍然以這種方式存在於父母的背景下,所以這就是我這樣做的方式。 – jporcenaluk

1

組這種方式創建DataContext的結合,它將綁定到一個屬性上mainViewModel:

DataContext="{Binding ChildVM, Source={StaticResource mainViewModel}}" 
+0

這並不像我想的那樣工作。我用這個,它使我的原始ParentViewModel不是一個孩子,而是一個不同的ChildVM。 所以,基本上,如果我嘗試發回一個命令,它不知道在ParentViewModel中設置了哪些屬性。 – jporcenaluk

2

您可以設置這些控件的共同父類,如dkozl上的DataContext建議。但是,如果該子視覺樹是比較大的,你應該考慮制定一個專門爲您的childVM用戶控件:

<Grid> 
    <ChildControl DataContext={Binding ChildVM}/> 
</Grid> 

<UserControl x:Class="ChildControl"> 
    <Grid> 
     <Button Content="{Binding SomeProperty}"/> 
     <Button Content="{Binding AnotherChildProperty}"/> 
    </Grid> 
</UserControl>