我正在使用一個附屬屬性來從TextBlock對TargetUpdated事件進行subscrive,所以我可以在每次文本更改時收到通知。WPF TargetUpdated事件沒有觸發ContentControl
使用下面的XAML:
<DataTemplate DataType="{x:Type targetUpdatedApp:Item}">
<targetUpdatedApp:LabelControl Text="{Binding Text, NotifyOnTargetUpdated=True}" Style="{StaticResource LabelTemplateStyle}"/>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox ItemsSource="{Binding Items}">
<!--<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Text, NotifyOnTargetUpdated=True}" targetUpdatedApp:DesiredWidth.DesiredMinWidth="120"/>
</DataTemplate>
</ListBox.ItemTemplate>-->
</ListBox>
<Button Click="ButtonBase_OnClick">Button</Button>
</StackPanel>
這裏是我的AttachedProperty代碼:
public class DesiredWidth
{
public static readonly DependencyProperty DesiredMinWidthProperty =
DependencyProperty.RegisterAttached(
"DesiredMinWidth", typeof (double),
typeof (TextBlock), new PropertyMetadata(OnDesiredMinWidthChanged));
public static double GetDesiredMinWidth(DependencyObject obj)
{
return (double) obj.GetValue(DesiredMinWidthProperty);
}
public static void SetDesiredMinWidth(DependencyObject obj, double value)
{
obj.SetValue(DesiredMinWidthProperty, value);
}
static void OnDesiredMinWidthChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var textBlock = obj as TextBlock;
if (textBlock == null)
{
return;
}
if (args.NewValue != null)
{
textBlock.TargetUpdated += OnTextBoxTargetUpdated;
}
}
static void OnTextBoxTargetUpdated(object sender, System.Windows.Data.DataTransferEventArgs e)
{
if (e.Property == TextBlock.TextProperty)
{
}
}
}
綁定到ListBox
的Items集合是ObservableCollection
,其上的項目實現了INotifyPropertyChanged
。 如果我取消註釋ListBox.ItemTemplate
的代碼並使用它代替風格,它的工作正常,但我使用的LabelControl(基本上有一個文本DependencyProperty
)描述的風格TargetUpdated
事件訂閱AttachedProperty
永遠不會被解僱。
有人可以給我一些關於這個問題的幫助嗎? 在此先感謝。
PS:從留言補充:
<Style x:Key="LabelTemplateStyle" TargetType="{x:Type argetUpdatedApp:LabelControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type targetUpdatedApp:LabelControl}">
<TextBlock Text="{TemplateBinding Text}" TargetUpdatedApp:DesiredWidth.DesiredMinWidth="120"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
添加缺少的風格: <形式X:鍵= 「LabelTemplateStyle」 的TargetType = 「{x:類型targetUpdatedApp:LabelControl}」> 的ControlTemplate> –
如果你對問題的評論不是那麼好。更好閱讀 –