【问题标题】:Windows Phone - DependencyPropertiesWindows Phone - 依赖属性
【发布时间】:2011-08-08 19:24:51
【问题描述】:

我正在尝试让 UserControl 在 Windows Phone 7 中工作。我有一些我想绑定到的属性,但无论我是否将它们添加为 DependencyProperties,它们都不会被填充。我可以让它们工作的唯一方法是设置 DataContext 。我试过的代码是(对于一个属性):

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 继承有关,但我需要查看其余的视觉层次才能分辨。您可以将 Silverlight Spy 与 WP7 一起使用来询问可视化树并随时查看 DataContext 是什么。您是否在“输出”窗口中遇到任何绑定错误?
  • 谢谢,很棒的工具。 datacontext 似乎继承自父 ViewModel,通过 usercontrol 一直到 ta4rget 文本框。我仍然不明白为什么它没有绑定到依赖属性。见img600.imageshack.us/img600/2835/datactx.th.png

标签: silverlight data-binding windows-phone-7 dependency-properties datacontext


【解决方案1】:

我猜你的 TextBox 在你的 UserControl 里面。如果是这样,则 ElementName 绑定存在问题,如 here 所述。

基本上,您在其 XAML 中为 UserControl 指定的名称会被使用它的任何名称覆盖(即在您的页面中)。

解决方法是使用类似的东西:

<TextBox Grid.Row="1" Grid.Column="1" x:Name="nudMaxIngredients" Width="120" Text="{Binding Parent.MaximumItems,Mode=TwoWay,ElementName=LayoutRoot}" InputScope="Number" />

其中 LayoutRoot 是 UserControl 的 XAML 中的根控件。

此外,您对 MaximumItems 属性的第一种方法是正确的。

【讨论】:

  • 很高兴知道这是一个错误,而不是缺乏支持或其他原因。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-31
  • 1970-01-01
  • 2011-11-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多