WPF文本框绑定和换行符

时间:2009-07-14 11:00:45

标签: c# wpf binding textbox

我有一个文本框,我绑定到viewmodel的字符串属性。字符串属性在viewmodel中更新,它通过绑定在文本框中显示文本。

问题是我想在字符串属性中的一定数量的字符之后插入换行符,并且我希望换行符显示在文本框控件上。

我尝试在viewmodel中的字符串属性中追加\ r \ n但是换行符没有反映在文本框上(我在文本框中将Acceptsreturn属性设置为true)

任何人都可以提供帮助。

3 个答案:

答案 0 :(得分:6)

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

Line1
Line2

看起来像

Line1
Line2

来自Naoki

答案 1 :(得分: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的实例设置为DataContext的{​​{1}}。最后,Window的实施是:

Button_Click()

(我意识到视图不应该直接修改ViewModel的private void Button_Click(object sender, RoutedEventArgs e) { this.model.Text = "Hello\r\nWorld"; } 属性,但这只是一个快速的示例应用程序。)

这会在Text的第一行产生“Hello”字样,而“World”位于第二行。

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

答案 2 :(得分:0)

我喜欢@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。

相关问题