【发布时间】:2010-11-10 14:45:22
【问题描述】:
我有一个绑定到视图模型的字符串属性的文本框。字符串属性在视图模型中更新,并通过绑定在文本框中显示文本。
问题是我想在字符串属性中的一定数量的字符之后插入换行符,并且我希望在文本框控件上显示换行符。
我尝试在 viewmodel 的字符串属性中附加 \r\n,但换行符没有反映在文本框上(我在文本框内将 Acceptsreturn 属性设置为 true)
谁能帮忙。
【问题讨论】:
我有一个绑定到视图模型的字符串属性的文本框。字符串属性在视图模型中更新,并通过绑定在文本框中显示文本。
问题是我想在字符串属性中的一定数量的字符之后插入换行符,并且我希望在文本框控件上显示换行符。
我尝试在 viewmodel 的字符串属性中附加 \r\n,但换行符没有反映在文本框上(我在文本框内将 Acceptsreturn 属性设置为 true)
谁能帮忙。
【问题讨论】:
我的解决方案是使用 HTML 编码的换行符( )。
Line1 Line2
看起来像
Line1
Line2
来自直树
【讨论】:
我刚刚创建了一个简单的应用程序,可以按照您的描述进行操作,并且对我有用。
XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<TextBox Grid.Row="0" AcceptsReturn="True" Height="50"
Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Button Grid.Row="1" Click="Button_Click">Button</Button>
</Grid>
</Window>
视图模型:
class ViewModel : INotifyPropertyChanged
{
private string text = string.Empty;
public string Text
{
get { return this.text; }
set
{
this.text = value;
this.OnPropertyChanged("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
var eh = this.PropertyChanged;
if(null != eh)
{
eh(this, new PropertyChangedEventArgs(propName));
}
}
}
ViewModel 的实例设置为Window 的DataContext。最后Button_Click()的实现是:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.model.Text = "Hello\r\nWorld";
}
(我意识到视图不应该直接修改 ViewModel 的 Text 属性,但这只是一个快速示例应用程序。)
这导致TextBox 的第一行出现单词“Hello”,第二行出现“World”。
也许如果您发布您的代码,我们可以看到与此示例有什么不同?
【讨论】:
我喜欢@Andy Approach,它非常适合小文本而不是大且可滚动的文本。
查看模型
class ViewModel :INotifyPropertyChanged
{
private StringBuilder _Text = new StringBuilder();
public string Text
{
get { return _Text.ToString(); }
set
{
_Text = new StringBuilder( value);
OnPropertyChanged("Text");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propName)
{
var eh = this.PropertyChanged;
if(null != eh)
{
eh(this,new PropertyChangedEventArgs(propName));
}
}
private void TextWriteLine(string text,params object[] args)
{
_Text.AppendLine(string.Format(text,args));
OnPropertyChanged("Text");
}
private void TextWrite(string text,params object[] args)
{
_Text.AppendFormat(text,args);
OnPropertyChanged("Text");
}
private void TextClear()
{
_Text.Clear();
OnPropertyChanged("Text");
}
}
现在您可以在 MVVM 中使用 TextWriteLine、TextWrite 和 TextClear。
【讨论】: