WPF ItemsControl绑定到UserControl

时间:2012-04-17 19:37:51

标签: wpf entity-framework user-controls itemscontrol

我有一个WPF应用程序,我需要做类似的事情:

<ItemsControl x:Name="lstProducts">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <TextBlock Text="{Binding ProductName}" />
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

我在这样的代码中设置ItemsSource:lstProducts.ItemsSource = MyEFContext.Products;

到目前为止一切正常。现在,我想使用自己的 UserControl 来显示产品,而不是像 TextBlock 那样。

<ItemsControl x:Name="lstProducts">
   <ItemsControl.ItemTemplate>
      <DataTemplate>
         <my:ProductItemCtl ProductName="{Binding ProductName}" />
      </DataTemplate>
   </ItemsControl.ItemTemplate>
</ItemsControl>

在我的userControl中,我创建了一个DependencyProperty(见下文),我在ProductName回调中设置了OnProductNameChanged

绑定TextBlock时,我的usercontrol中的ItemsControl未更新,并且未启动回调。

#region ProductName

        /// <summary>
        /// ProductName Dependency Property
        /// </summary>
        public static readonly DependencyProperty ProductNameProperty =
            DependencyProperty.Register("ProductName", typeof(String), typeof(ProductItemCtl),
                new FrameworkPropertyMetadata("",
                    new PropertyChangedCallback(OnProductNameChanged)));

        /// <summary>
        /// Gets or sets the ProductName property. This dependency property 
        /// indicates ....
        /// </summary>
        public String ProductName
        {
            get { return (String)GetValue(ProductNameProperty); }
            set {  SetValue(ProductNameProperty, value); }
        }

        /// <summary>
        /// Handles changes to the ProductName property.
        /// </summary>
        private static void OnProductNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ProductItemCtl target = (ProductItemCtl)d;
            String oldProductName = (String)e.OldValue;
            String newProductName = target.ProductName;
            target.OnProductNameChanged(oldProductName, newProductName);
        }

        /// <summary>
        /// Provides derived classes an opportunity to handle changes to the ProductName property.
        /// </summary>
        protected virtual void OnProductNameChanged(String oldProductName, String newProductName)
        {
            // Set Product Name in the display Here!
            this.txtProductName.Text = newProductName;
        }

        #endregion

2 个答案:

答案 0 :(得分:0)

不是答案,但我不能将此作为评论。如果您简化代码会发生什么:

public static readonly DependencyProperty ProductNameProperty = DependencyProperty.Register(
    "ProductName", typeof(string), typeof(ProductItemCtl), 
    new FrameworkPropertyMetadata(string.Empty,
        (o, e) => ((ProductItemCtl)o).txtProductName.Text = (string)e.NewValue)); 

答案 1 :(得分:0)

Arrrghhh得到了它...我在UserControl的构造函数中有this.ProductName = "";

我浪费了这么多时间......并且抱歉浪费了你们所有人。

因为我通过尝试你的代码Clemens发现我会将你的答案标记为“已回答”。

谢谢大家。