私はそのようなことをする必要がある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
をバインドするときにユーザーコントロールのが更新されず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