我正在構建Windows Phone 7應用程序。所以,我正在使用SilverLight 3(.7),並且我對構建的UserControls有點問題。下面是我現在怎麼做:在WP7 UserControl中執行DataBinding的正確方法
用戶控件有一個DependencyProperty命名編號
<UserControl x:Class="MyUserControl" x:Name="myUserControl">
<TextBlock Text="{Binding ElementName=myUserControl, Path=Number}"/>
</UserControl>
要使用它,我只是做:
<MyUserControl Number="{Binding ElementName=MyPage, Path=SomeNumber}">
<MyUserControl Number="{Binding ElementName=MyPage, Path=SomeOtherNumber}">
這一切的偉大工程,但如果我爲我的控件的兩個實例之一添加一個名稱,事情變得古怪。例如:
<MyUserControl x:Name="SomeNumberControl"
Number="{Binding ElementName=MyPage, Path=SomeNumber}">
<MyUserControl Number="{Binding ElementName=MyPage, Path=SomeOtherNumber}">`
然後數據不顯示出來。看來給定的名稱會覆蓋UserControl中指定的名稱,並且綁定不起作用。
所以,我試圖通過datacontext做綁定。並將DataContext設置爲UserControl。
所以,我的控制成爲:
<UserControl x:Class="MyUserControl"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<TextBlock Text="{Binding Number}"/>
</UserControl>
有了這個沒有被束縛。這就像datacontext從來沒有設置,甚至當我把這個控件放在我創建的另一個用戶控件中時,我們看起來父控件現在已經綁定到了MyUserControl實例。
所以,當我做到以下幾點:在類型的MyUserControl未發現
<MyPage>
<MyUserControl Number={Binding SomeNumber}"/>
我得到的錯誤,
SomeNumber。
就好像父控件的綁定現在是MyUserControl的實例。我只是在做我的用戶控件中綁定操作的根本錯誤,或者SilverLight 4和WP7有點奇怪。
對此非常感謝。
邁克爾嗨, 感謝您的文章,我遇到了** ** SAME準確的問題。當我給我的用戶控件一個x:Name時,數據綁定停止工作。 不幸的是,我不明白你的意思**我改變了所有引用被命名爲參考,現在可** 能否請您詳細闡述。 謝謝:) – 2011-02-19 13:47:32
`DataContext =「{Binding RelativeSource = {RelativeSource Self}}」`是代碼味道。 – Will 2012-02-19 18:06:45