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

How to put editable text in static text paragraph in WPF

我想要实现的目标在 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?

WPF 和 XAML 与 HTML 不同,都是关于 data.

思考和推理任何基于 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();
    }
}

结果:

请注意,我根本不是 "touching" 代码中的 UI,这只是简单、简单的属性和 DataBinding。