[英]Binding to dependency property
我有一個簡單的自定義用戶控件:
<Grid x:Name="LayoutRoot">
<StackPanel>
<TextBlock Text="{Binding DisplayText}"/>
<TextBlock Text="{Binding PersonName}"/>
</StackPanel>
</Grid>
我在MainPage.xaml中使用它,如下所示:
<local:WindowsPhoneControl1 x:Name="customControl" DisplayText="test">
</local:WindowsPhoneControl1>
如果在MainPage.xaml.cs中,我會執行以下操作:
PersonName = "George";
customControl.DataContext = this;
然后喬治顯示出來,但測試不是。 這是有道理的,但我不知道如何綁定到DisplayText屬性。
當然,以下內容將不起作用,因為不會顯示喬治 :
customControl.DataContext = customControl;
請注意,這應該適用於WP / silverlight開發,因此AncestorType之類的內容可能不可用(並非一定有用)。
可能有多種方法可以做到這一點。 這是一個:在PersonName
的用戶控件中添加一個Dependency屬性,為DisplayText
一個常規的屬性(由於沒有綁定DP,因此不需要DP)。
public static readonly DependencyProperty =
DependencyProperty.Register("PersonName", typeof(string), typeof(MyUserControl), null);
public string DisplayText { get; set; }
public string PersonName
{
get { return (string)GetValue(PersonNameProperty); }
set { SetValue(PersonNameProperty, value); }
}
然后,將用戶控件的DataContext
設置為LayoutRoot
(在構造函數中初始化之后)。
public MyUserControl()
{
InitializeComponent();
LayoutRoot.DataContext = this;
}
編輯下面的方法可能更簡單(肯定是更直接的),但是需要Silverlight5。您可以使用RelativeSource
通過使用屬性綁定到DisplayText
屬性。
<TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=UserControl},
Path=DisplayText}"/>
因此,此處用戶控件的DataContext仍可以設置為MainPage
,並且可以將這一元素的數據源指向用戶控件的代碼隱藏類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.