【问题标题】:Binding and support for rich text formatting绑定和支持富文本格式
【发布时间】:2012-11-11 05:49:00
【问题描述】:

考虑以下场景:

  • 我有一个使用DataContext 绑定到ObservableCollectionListView

    <ListView ItemsSource="{Binding}">
    

    包含string 数据的class 使用DependencyProperty 机制来保持显示的内容与数据集合同步。

  • ListView 有一列是可编辑的(我按照教程here 来实现这一点);然后ListViewItemTextBlockTextBox。这是使用 DataTemplate 和两个 Style 资源完成的。
  • 我想根据搜索字符串格式化TextBlock 中显示的字符串。具体来说,如果有匹配项,我想将ListView 的项目格式化为当用户在他们的搜索查询中键入时变为粗体(只有按顺序匹配的字符才应该变为粗体)。这只需要为当前使用TextBlock 呈现的文本(即当前未编辑的文本)显示。

我考虑过使用IMultiValueConverter,它接受对呈现数据的TextBlock 的引用,以便我可以适当地格式化文本。但是,这会破坏我设置的绑定:

<TextBlock.Text>
  <MultiBinding Converter="{StaticResource searchFormatter}" ConverterParameter="{x:Reference Name=txtSearch}">
    <MultiBinding.Bindings>
      <Binding Path="NameOfBoundDependencyProperty"/>
      <Binding RelativeSource="{RelativeSource Self}"/>
    </MultiBinding.Bindings>
  </MultiBinding>
</TextBlock.Text>

searchFormatterIMultiValueConvertertxtSearch 是包含搜索查询的 TextBox

我仍在学习 WPF,所以我不熟悉最佳方法或可能的方法。有没有办法保持数据绑定(以便编辑反映在集合和 ListView 中)并且仍然以不同的方式向用户表示数据(以便搜索匹配可能是粗体)?如果我手动管理绑定可能会更干净?

【问题讨论】:

    标签: c# wpf listview binding .net-4.5


    【解决方案1】:

    我决定使用支持 HTML 的 Control,以便我可以使用 IValueConverter 即时更新显示文本的值,而不会影响任何活动绑定。我使用了来自here 的代码并对其进行了修改,使其看起来像我的ListView 中的TextBlock

    BorderBrush = Brushes.Transparent;
    SelectionBrush = Brushes.Transparent;
    Cursor = Cursors.Arrow;
    BorderThickness = new Thickness(0);
    Background = Brushes.Transparent;
    

    但是,我仍然需要触发IValueConverter,以便在用户输入搜索查询时更新显示(代码来自here):

    ICollectionView view = CollectionViewSource.GetDefaultView(ItemsSource);
    view.Refresh();
    

    我不想减慢搜索过程,所以我只在实际匹配时强制刷新(或者匹配状态变为不匹配)。我的IValueConvertor 只是插入了粗体标签来匹配搜索查询:

    <RichTextBox Text="{Binding Path=DisplayItem, Converter={StaticResource searchFormatter}, ConverterParameter={x:Reference txtSearch}}"/>
    

    这次searchFormatterIValueConvertor

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      相关资源
      最近更新 更多