首页 > 解决方案 > 在 TextBlock 的 ObservableCollection 中,是否可以通过编程方式选择 TexBlock 中的文本?

问题描述

我有一个包含 TextBlock 的“DataItem”的 ObservableCollection。想法是通过 ContentControl 将 ObservableCollection 绑定到 ListView。我希望能够以编程方式操作 TextBlocks,并将这些更改反映在演示文稿中,这似乎是最有效的方法。

我用几个 DataItem 对象填充 ObservableCollection,并将文本数据添加到每个 TextBlock。然后我尝试以编程方式选择 TextBlock 中的一段文本。

public class DataItem: INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string propertyName = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    private readonly TextBlock tb;
    public TextBlock TB
    {
        get { return tb; }
    }

    public DataItem()
    {
        tb = new TextBlock
        {
            TextWrapping = Windows.UI.Xaml.TextWrapping.Wrap,
            IsTextSelectionEnabled = true,
            SelectionHighlightColor = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.Orange)
        };
    }
}

private ObservableCollection<DataItem> DataItems { get; set; } = new ObservableCollection<DataItem>();

// 然后在 OnNavigatedTo()...

for (int i = 0; i < 5; i++)
{
    DataItem dataItem = new DataItem();
    dataItem.TB.Text = string.Format("This is sentence Number {0}", i);
    DataItems.Add(dataItem);
}

MyListView.ItemsSource = DataItems;

// 这是 XAML 部分...

<ListView x:Name="MyListView">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
             <ItemsWrapGrid MaximumRowsOrColumns="7" Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
        <DataTemplate x:DataType="local:DataItem">
            <ContentControl Content="{Binding TB, Mode=OneWay}"/>
        </DataTemplate>
    </ListView.ItemTemplate>        
</ListView>

// 最后,这是尝试选择的代码:

TextPointer pos = DataItems[2].TB.ContentStart;
TextPointer beg = pos.GetPositionAtOffset(4, LogicalDirection.Forward);
TextPointer end = pos.GetPositionAtOffset(8, LogicalDirection.Backward);

try
{
    DataItems[2].TB.Select(beg, end);
}
catch(Exception exc)
{
    string s = exc.Message.ToString();
}

调试器甚至没有到达 Catch 块。操作系统显示: System.AccessViolationException: '试图读取或写入受保护的内存。这通常表明其他内存已损坏。

不能通过这种方法在 TextBlock 中选择一段文本吗?你会提出什么其他策略?

标签: c#xamlobservablecollectiontextblock

解决方案


推荐阅读