在web应用程序中,我试图实现的目标有些简单,但我一直在努力在WPF中实现它。
我想在WPF中加载一段文字,并用可编辑的文本框替换它的一些特定单词。我怎么能这么做?
什么是最好的策略,使这是一个正确的清洁方式?
更新:
请考虑以下案文。我想在WPF中显示它,而不是粗体字,放一些文本框。
你认识一个有钱有名的人吗?他是自信、受欢迎和快乐的整个of的时代-主流成功的缩影?或者,on,另一方面,他是否有压力,对他的人生选择有了第二次思考,而不确定他的生命的意义?
发布于 2015-09-03 16:24:55
与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();
}
}
结果:
注意,我根本没有在代码中“触摸”UI,这只是简单的属性和DataBinding。
https://stackoverflow.com/questions/32379738
复制相似问题