WPF文本框绑定和换行
问题描述:
我有一个文本框,我绑定到viewmodel的字符串属性。字符串属性在viewmodel中更新,并通过绑定显示文本框内的文本。WPF文本框绑定和换行
问题是,我想在字符串属性中的一定数量的字符后插入换行符,我希望换行符显示在文本框控件上。
我试图附加\ r \ n的视图模型的字符串属性,但断行内不会反映在文本框(我有Acceptsreturn属性设置为true的文本框内)
任何人可以帮助。
答
我刚刚创建了一个简单的应用程序,它可以完成您所描述的任务,并且可以为我工作。
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
一个实例被设置为DataContext
为Window
。最后,Button_Click()
实现如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.model.Text = "Hello\r\nWorld";
}
(我意识到观点实在不应该直接修改视图模型的Text
属性,但是这仅仅是一个快速的示例应用程序。)
这将导致TextBox
的第一行是“Hello”,第二行是“World”。
也许如果您发布您的代码,我们可以看到与此示例有什么不同?
答
我的解决方案是使用HTML编码的换行符( )。
Line1 Line2
貌似
Line1
Line2
从直树
答
我喜欢@Andy方法,它是完美的小文不与大和滚动文本。
视图模型
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");
}
}
现在你可以使用TextWriteLine,TextWrite和TextClear在MVVM。
谢谢安迪,我终于明白了这个问题。非常感谢您的支持。 – deepak 2009-07-14 12:40:34