Tôi vừa tạo một ứng dụng đơn giản thực hiện những gì bạn mô tả và nó hoạt động cho tôi.
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>
ViewModel:
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));
}
}
}
Một thể hiện của ViewModel
được thiết lập như là DataContext
cho Window
. Cuối cùng, việc thực hiện Button_Click()
là:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.model.Text = "Hello\r\nWorld";
}
(Tôi nhận ra rằng quan điểm nên không thực sự thay đổi sở hữu Text
của ViewModel trực tiếp, nhưng đây chỉ là một ứng dụng mẫu nhanh chóng.)
Điều này dẫn đến từ "Xin chào" trên dòng đầu tiên của số TextBox
và "Thế giới" nằm trên dòng thứ hai.
Có thể nếu bạn đăng mã, chúng tôi có thể thấy điều gì khác với mẫu này?
Cảm ơn Andy, tôi đã tìm ra vấn đề ở phần cuối của mình. Cảm ơn bạn rất nhiều vì đã ủng hộ bạn. – deepak