2010-02-01 14 views
0

我有一個子控件嵌入我的主控制器,它允許用戶編輯地址。因爲這是重複使用所有的地方(有時在多個位置上的一個控制),我結合它像這樣如何將數據綁定到控件的屬性而不是datacontext?

<Controls:EditAddressUserControl DataContext="{Binding Path=HomeAddress}"/> 
<Controls:EditAddressUserControl DataContext="{Binding Path=WorkAddress}"/> 

但EditAddressUserControl需要訪問CountrySummary對象的主要控制的列表,以便它可以選擇哪個國家的地址屬於。

我添加了一個國家的DependencyProperty到EditAddressUserControl並添加

Countries="{Binding Countries}" 

到目前爲止,一切都進展順利,該EditAddressUserControl.Countries酒店有正確的國家吧。但是,如何將我的Combobox.ItemsSource綁定到XAML中?

我仍然希望EditAddressUserControl上的所有東西都綁定到它的DataContext,但是ComboBoxCountries.ItemsSource需要綁定到「this.Countries」。

我如何做到這一點?

我已經試過這

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:EditAddressUserControl}}, Path=Countries}" /> 

我看到在輸出框中沒有約束力的錯誤,但我也看到在下拉列表中沒有物品。

+0

是「EditAddressUserControl」的子控件還是父控件?你應該在AncestorType中指定父親 – arconaut 2010-02-01 19:40:37

+0

EditAddressUserControl是嵌入式控件 – 2010-02-02 10:35:47

回答

1

您可以通過將RelativeSource用於綁定源而不是DataContext來完成此操作。

這最有可能是這個樣子:

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Controls:EditAddressUserControl}}, Path=Countries}" /> 
+0

嘗試過它,但不幸的是它沒有工作。 – 2010-02-01 19:23:47

+0

只要您正確設置,這將起作用。您需要獲取相關的來源,以便在定義DP的祖先層次結構中「查找」適當的類。我根據你放置的內容猜測了語法。 – 2010-02-01 19:49:40

0

這樣做是完全停止使用的DataContext的方式。相反,我在父控制,而不是設置的DataContext =「...」我把地址添加一個DependencyProperty到我的控制

public static DependencyProperty AddressProperty = DependencyProperty.Register("Address", typeof(EditPostalAddressDto), typeof(EditPostalAddressControl)); 

然後=「...」 - 那麼該控件的XAML更改爲包括綁定上的ElementName

<UserControl ..... x:Name="MainControl"> 
<TextBox Text="{Binding ElementName=MainControl,Path=Address.Region}"/> 

現在我可以專門綁定到Address屬性,但也綁定到主數據上下文的屬性。

相關問題