我的英语能力很差,因为我不会说英语。
我已经按照以下在TextBox控件上运行的行为创建了。该行为具有一个名为Items的集合类型DP。
class HighlightBehavior : Behavior<TextBox>
{
public List<TextStyle>Items
{
get { return (List<TextStyle>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(List<TextStyle>), typeof(HighlightBehavior), new PropertyMetadata(ItemsChanged));
private static void ItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// break point
}
}
而且...我已经创建了一个MainWindow,用作上述行为的以下代码。
<MainWindow>
<TextBox>
<i:interaction.Behaviors>
<behavior:HighlightBehavior/>
</i:interaction.Behavior>
</TextBox>
</MainWindow>
而且我已经编写了一个MainWindowViewModel,它具有一个名为HighlightItems的集合类型DP。
class MainWindowViewModel : ViewModelBase
{
public List<TextStyle> HighlightItems
{
get { return (List<TextStyle>)GetValue(HighlightItemsProperty ); }
set { SetValue(HighlightItemsProperty , value); }
}
public static readonly DependencyProperty HighlightItemsProperty =
DependencyProperty.Register("HighlightItems", typeof(List<TextStyle>), typeof(HighlightBehavior), new PropertyMetadata(null));
public MainWindowViewModel()
{
SetValue(HighlightItemsProperty, new List<TextStyle>());
}
}
并且我将MainWindowViewModel绑定到MainWindow,并将MainWindowViewModel的HighlightItems(DP)与HighlightBehavior的Items(DP)连接起来,如下代码。
<MainWindow>
<TextBox>
<i:interaction.Behaviors>
<behavior:HighlightBehavior Items="{Binding HighlightItems, Mode=TwoWay}"/>
</i:interaction.Behavior>
</TextBox>
</MainWindow>
总而言之,结构如下图。
我希望每当更改项目时,都会调用HighlightBehavior的ItemsChanged。但是它没有被调用。
每当HighlightBehavior的集合类型DP(Items)更改时,我都希望收到通知。我必须怎么做才能达到这个目标?
谢谢您的阅读。我将等待答案。
我相信您正在寻找的是ObservableCollection。这是一种特殊的集合,每当添加,删除,更改或移动一项时,它都会引发其CollectionChanged
事件。
我建议以下内容:
而不是将HighlightItems
声明为List<TextStyle>
,而是将其声明为ObservableCollection<TextStyle>
。
向HighlightBehavior
添加另一种方法来处理CollectionChanged
,例如:HighlightItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
只要设置了ItemsChanged
,就会调用您当前的HighlightItems
实现。使用它将事件处理程序附加到CollectionChanged
,如下所示:
var col = (ObservableCollection<TextStyle>)e.NewValue;
if (col != null) { col.CollectionChanged += HighlightItemsCollectionChanged; }
HighlightItems
设置为一次以上,请不要忘记将任何现有的事件处理程序删除到先前的集合中。您可以将其与之前的代码段一起添加到ItemsChanged
:col = (ObservableCollection<TextStyle>)e.OldValue;
if (col != null) { col.CollectionChanged -= HighlightItemsCollectionChanged; }
HighlightItemsCollectionChanged
现在将在从HighlightItems
中添加或删除项目时被调用。在此方法中需要执行的所有操作,或者如果您希望代码在替换集合本身时也能运行,则可以使另一个方法实际执行所需的操作,然后从ItemsChanged
和[ C0]。谢谢。我已根据您的建议更改了代码,现在,当更改集合的元素时,我会收到通知。