我刚刚创建了一个简单的应用程序,完成了你描述的功能,并且它对我有效。
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”。
也许如果你发布你的代码,我们可以看到与此示例有何不同?