c# - 在 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 中选择一段文本吗?你会提出什么其他策略?
解决方案
推荐阅读
- mysql - 升级到 MySQL 8。从服务器接收到字段“255”的未知字符集索引。例外
- class - 初始化 JAXB 以解组到外部类定义
- python - Pyinstaller - 多个 python 脚本
- javascript - 关闭浏览器窗口,其中单击按钮时的角度应用程序
- javascript - 将组件定位在 .jsx 文件中,而不是通过 .css 文件
- xml - 为什么从 XML 导入 Access 数据库时数据会被截断
- python-3.x - 出现错误“无法导入 PIL.Image。使用 `array_to_img` 需要 PIL。”
- hashicorp-vault - Vault,如何强制在特定策略下创建令牌?
- reactjs - 在没有 Redux 的兄弟姐妹之间传递数据
- python-sphinx - :ref: 链接不给链接