我試圖讓Windows Phone 7中的用戶控件工作。我有幾個屬性,我想要綁定到,但他們不填充無論我是否將它們添加爲DependencyProperties或不。我可以讓他們工作的唯一方法就是設置DataContext。我試過的代碼是(對於一個屬性):Windows Phone - DependencyProperties
public static readonly DependencyProperty MaximumItemsProperty = DependencyProperty.Register("MaximumItems", typeof(int), typeof(ManageIngredientsControl), new PropertyMetadata(0));
/// <summary>
/// Gets or sets the maximum number of items to match.
/// </summary>
/// <value>The maximum number of items to match.</value>
public int MaximumItems
{
get { return Convert.ToInt32(base.GetValue(MaximumItemsProperty)); }
set { base.SetValue(MaximumItemsProperty, value); }
}
<TextBox Grid.Row="1" Grid.Column="1" x:Name="nudMaxIngredients" Width="120" Text="{Binding MaximumItems,Mode=TwoWay,ElementName=root}" InputScope="Number" />
根UserControl元素被稱爲'root',但該值未被填充。得到一半的工作的唯一方法是通過使用這樣的:
public int MaximumItems
{
get { return Convert.ToInt32(DataContext) }
set { DataContext = value; }
}
似乎有什麼地方的干擾與DataContext的,但如果我綁定到DependencyProperties它爲什麼會事?
這可能與DataContext繼承有關,但我需要查看其餘的視覺hiearchy能夠告訴。您可以將Silverlight Spy與WP7一起用於查詢可視化樹,並查看DataContext在任何時候的用途。輸出窗口中是否有任何綁定錯誤? – 2011-04-19 15:52:27
謝謝,優秀的工具。 datacontext似乎從父視圖模型繼承,通過用戶控件並繼續到ta4rget文本框。我仍然不明白爲什麼它不綁定到依賴項屬性。見http://img600.imageshack.us/img600/2835/datactx.th.png – Echilon 2011-04-19 16:25:08