gpt4 book ai didi

c# - 如何在WPF中的静态文本段落中放置可编辑文本

转载 作者:太空宇宙 更新时间:2023-11-03 21:18:37 27 4
gpt4 key购买 nike

我想要实现的目标在 Web 应用程序中有些容易,但我一直在努力在 WPF 中实现。

我想在 WPF 中加载一段文本,并用可编辑的文本框替换其中的一些特定单词。我该怎么做?

以正确、干净的方式实现这一点的最佳策略是什么?

更新:

考虑以下文本。我想在 WPF 中显示它,而不是粗体字,而是放置一些文本框。

Do you know someone rich and famous? Is he confident, popular, and joyful all of the time—the epitome of mainstream success? Or, on the other hand, is he stressed, having second thoughts about his life choices, and unsure about the meaning of his life?

最佳答案

与 HTML 不同,WPF 和 XAML 都是关于数据的。

思考和推理任何基于 XAML 的 UI 的最佳方式是思考您需​​要显示和交互的数据

在这种情况下:

public class Word
{
public string Value { get; set; }

public bool IsEditable { get; set; }
}

代表我们的每一个词。然后你只需要这些列表:

public class ViewModel
{
public List<Word> Words { get; private set; }

public ViewModel()
{
var editableWords = new[] { "on", "of" };

var text = "Do you know someone rich and famous? Is he confident, popular, and joyful all of the time—the epitome of mainstream success? Or, on the other hand, is he stressed, having second thoughts about his life choices, and unsure about the meaning of his life?";

this.Words =
text.Split(' ')
.Select(x => new Word
{
Value = x,
IsEditable = editableWords.Contains(x.ToLower())
})
.ToList();
}
}

注意我是如何将文本变成 List<Word> 的和设置 IsEditable在需要的地方。

现在只需使用 ItemsControl 即可显示这些:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis"/>
</Window.Resources>
<ItemsControl ItemsSource="{Binding Words}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Margin="5,2,5,2">
<TextBlock Text="{Binding Value}"
VerticalAlignment="Center"/>
<TextBox Text="{Binding Value}"
Visibility="{Binding IsEditable, Converter={StaticResource BoolToVis}}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>

最后,设置DataContext到我们的 ViewModel 的一个实例:

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

DataContext = new ViewModel();
}
}

结果:

enter image description here

请注意,我根本没有在代码中“接触”UI,这只是简单、简单的属性和 DataBinding。

关于c# - 如何在WPF中的静态文本段落中放置可编辑文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32379738/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com