我有一个WPF应用程序,我需要做这样的事情:WPF的ItemsControl绑定到用户控件
<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>
在我的用户,我创建了一个DependencyProperty
那样(见下文),我在OnProductNameChanged
回调设置ProductName
。
在绑定ItemsControl
时,我的用户控件中的TextBlock
没有更新,并且回调没有启动。
#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
是否将Mode = TwoWay添加到您的用户控件帮助的绑定上?另外,为什么你在代码中设置文本框的文本(在OnProductNameChanged中)?为什么不绑定它? – 2012-04-17 19:41:56
不是'DependencyProperty.Register(“ProductName”,typeof(String),typeof(AchatItem)''实际上应该有'typeof(ProductItemCtl)'而不是'typeof(AchatItem)'' – 2012-04-17 19:45:13
没有TwoWay不会改变任何东西。我在这里简化了代码,只是为了隔离这个问题,在真正需要做更多的事情,而不仅仅是设置文本值 – danbord 2012-04-17 19:45:41