我正在尝试创建一个显示格式化文本的列表框。我希望能够更改代码的格式。
为了显示格式化文本,我选择了 TextBlock 并打算使用 TextBlock.Inlines 集合进行格式化。 TextBlock.Inlines 不可绑定,所以我创建了新类可绑定文本块派生自 TextBlock。该类有一个依赖属性内联列表我试图绑定到内联科尔模型中的 ObservableCollection。
问题是变化内联科尔不要通知我的内联列表关于 PropertyChanged 事件。绑定仅在以下时间起作用一次可绑定文本块对象创建时间及其之后。
有什么想法吗?
XAML:
<ListBox x:Name="PART_lb" VerticalAlignment="Stretch" ItemsSource="{Binding ItemColl}"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto" >
<ListBox.ItemTemplate>
<DataTemplate>
<local:BindableTextBlock InlineList="{Binding Path=InlinesColl}" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
BindableTextBlock 类:
public class BindableTextBlock : TextBlock
{
public ObservableCollection<Inline> InlineList
{
get { return (ObservableCollection<Inline>)GetValue(InlineListProperty); }
set { SetValue(InlineListProperty, value); }
}
public static readonly DependencyProperty InlineListProperty =
DependencyProperty.Register("InlineList", typeof(ObservableCollection<Inline>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnPropertyChanged));
private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
BindableTextBlock textBlock = (BindableTextBlock)sender;
textBlock.Inlines.Clear();
textBlock.Inlines.AddRange((ObservableCollection<Inline>)e.NewValue);
}
}
模型类
public class TextBlockModel
{
ObservableCollection<Inline> _inlinesColl = new ObservableCollection<Inline>();
public ObservableCollection<Inline> InlinesColl
{
get { return _inlinesColl; }
set {_inlinesColl = value; }
}
}
带有 ListBox ItemSsource 集合的 ViewModel
ObservableCollection<TextBlockModel> _itemColl = new ObservableCollection<TextBlockModel>();
public ObservableCollection<TextBlockModel> ItemColl
{
get { return _itemColl; }
set { _itemColl = value; }
}
测试项目here