我正在制作一个UWP,无法正确掌握DataBinding
和INotifyPropertyChanged
我正在尝试将ContentDialog
中的某些TextBox
绑定到我的代码Behind CS文件中的属性。
这是我的视图模型:
class UserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public string _fname { get; set; }
public string _lname { get; set; }
public string Fname
{
get { return _fname; }
set
{
_fname = value;
this.OnPropertyChanged();
}
}
public string Lname
{
get { return _lname; }
set
{
_lname = value;
this.OnPropertyChanged();
}
}
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
代码背后:
public sealed partial class MainPage : Page
{
UserViewModel User { get; set; }
public MainPage()
{
this.InitializeComponent();
User = new UserViewModel();
}
....
....
private void SomeButton_Click(object sender, TappedRoutedEventArgs e)
{
//GetUserDetails is a static method that returns UserViewModel
User = UserStore.GetUserDetails();
//show the content dialog
ContentDialogResult result = await UpdateUserDialog.ShowAsync();
}
}
这是ContentDialog
的XAML:
<ContentDialog Name="UpdateUserDialog">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"></ColumnDefinition>
<ColumnDefinition Width="1*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Grid.Row="0"
Grid.Column="0"
Grid.ColumnSpan="2"
Name="tbFirstNameUpdate"
Text="{x:Bind Path=User.Fname, Mode=OneWay}"
Style="{StaticResource SignUpTextBox}"/>
<TextBox Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Name="tbLastNameUpdate"
Text="{x:Bind Path=User.Lname, Mode=OneWay}"
Style="{StaticResource SignUpTextBox}"/>
</ContentDialog>
NOTE :当我像这样初始化 MainPage
构造函数中的视图模型时,绑定效果很好:
User = new UserViewModel { Fname = "name", Lname = "name" };
当您用新视图模型实例替换 User
属性的值时,您不会发射属性换事事件。
您可以简单地替换
User = UserStore.GetUserDetails();
var user = UserStore.GetUserDetails();
User.Fname = user.Fname;
User.Lname = user.Lname;
因此,更新视图模型的现有实例。
您应该将DataContext
属性设置为视图模型实例:
public MainPage()
{
this.InitializeComponent();
User = new UserViewModel();
DataContext = User;
}
请参阅:https://learn.microsoft.com/en-us/windows/uwp/uwp/data-binding/data-binding-in-depth