WPF文本框绑定和换行符

dee*_*pak 5 c# wpf binding textbox

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

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

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

任何人都可以帮忙.

Tha*_*.NQ 6

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

Line1
Line2
Run Code Online (Sandbox Code Playgroud)

好像

Line1
Line2
Run Code Online (Sandbox Code Playgroud)

从Naoki


And*_*ndy 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>
Run Code Online (Sandbox Code Playgroud)

视图模型:

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

的实例ViewModel被设置为DataContextWindow。最后的实现Button_Click()是:

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

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

这会导致 的第一行出现“Hello”一词TextBox,第二行出现“World”。

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