2010-04-27 60 views
3

我有一些代碼,看起來像這樣:是否有更簡單的方法將屬性綁定到所有者的DataContext?

<Expander Header="{Binding SelectedSlot.Name}" 
      Visibility="{Binding ShowGroupSlot, Converter={StaticResource BooleanToVisibility}}"> 
    <Controls:GroupPrototypeSlotControl Slot="{Binding DataContext.SelectedSlot, 
     RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}}" /> 
</Expander> 

這工作,但插槽綁定的醜陋困擾我。這是必需的,因爲GroupPrototypeSlotControl具有GroupPrototypeViewModel作爲其DataContext。如果我只是使用{Binding SelectedSlot},它會嘗試在'child'ViewModel上解析它,失敗。我通過明確地查看父控件的DataContext來解決這個問題。有沒有更好的方法來做這種綁定?


編輯:我發現一個更清潔的方式來解決我的問題,雖然它仍然感覺像一個黑客。我修改了GroupPrototypeSlotControl,使其具有頂層LayoutRoot(在本例中爲StackPanel),然後將LayoutRoot的DataContext設置爲ViewModel,而不是設置整個控件的DataContext。這允許我在使用控件時使用{Binding SelectedSlot}語法(因爲控件仍然具有父級DataContext),代價是略微增加了控件的複雜性。一般來說,這可能是自定義控件的更好的模式,因爲如果沒有明確指定控件,控件的使用者需要{Binding}來解析它們的父級DataContext。

回答

1

稍微清潔劑(短)的方法是使用ElementNameBinding這樣的:

<Expander Header="{Binding SelectedSlot.Name}" 
      x:Name="expander" 
      Visibility="{Binding ShowGroupSlot, Converter={StaticResource BooleanToVisibility}}"> 
    <Controls:GroupPrototypeSlotControl Slot="{Binding DataContext.SelectedSlot, ElementName=expander}" /> 
</Expander> 
相關問題