WPF文本框绑定和换行

5
我有一个文本框,我将其绑定到视图模型的字符串属性。字符串属性在视图模型中更新,并通过绑定在文本框中显示文本。
问题是,我想在特定数量的字符后插入换行符,并希望换行符显示在文本框控件上方。
我尝试在视图模型中的字符串属性中追加\r\n,但换行符没有反映在文本框中(我已将Acceptsreturn属性设置为true在文本框内)。
有人能帮忙吗?
3个回答

6
我的解决方案是使用HTML编码的换行符 ( )。
Line1
Line2

看起来像是

Line1
Line2

来自Naoki


3

我刚刚创建了一个简单的应用程序,完成了你描述的功能,并且它对我有效。

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的一个实例被设置为WindowDataContext。最后,Button_Click()的实现是:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.model.Text = "Hello\r\nWorld";
}

我知道视图不应该直接修改ViewModel的Text属性,但这只是一个快速的示例应用程序。

这会导致第一行TextBox上显示单词“Hello”,第二行上显示“World”。

也许如果你发布你的代码,我们可以看到与此示例有何不同?


谢谢Andy,我在我的端口解决了问题。非常感谢您的支持。 - deepak

0

我喜欢 @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");
    }
}

现在你可以在MVVM中使用TextWriteLine、TextWrite和TextClear了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接