Xaml 绑定到属性的UWP
我正在进行UWP,无法正确掌握Xaml 绑定到属性的UWP,xaml,data-binding,uwp,inotifypropertychanged,Xaml,Data Binding,Uwp,Inotifypropertychanged,我正在进行UWP,无法正确掌握数据绑定和INotifyPropertyChanged 我正在尝试将ContentDialog中的一些TextBox绑定到我的代码隐藏cs文件中的属性 这是我的视图模型: class UserViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged = delegate { }; public string _fname
数据绑定
和INotifyPropertyChanged
我正在尝试将ContentDialog
中的一些TextBox
绑定到我的代码隐藏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>
您应该将
DataContext
属性设置为视图模型实例:
public MainPage()
{
this.InitializeComponent();
User = new UserViewModel();
DataContext = User;
}
请参阅:当您使用新的视图模型实例替换
User
属性的值时,不会触发PropertyChanged事件
但是,您可以简单地替换
User = UserStore.GetUserDetails();
借
并因此更新视图模型的现有实例。请注意,这仅对
{Binding…}
是必需的,而对{x:Bind…}
不是必需的。这绝对有效。但是,当引用中的新ViewModel实例时,是否有方法触发PropertyChanged事件?因为我在视图模型中有更多属性。请为用户属性实现INotifyPropertyChanged。但是,我不确定x:Bind
是否会做出反应。试试看。无论如何,从架构的角度来看,我建议在单个VM实例上进行操作。使GetUserDetails成为VM类的实例方法,或将VM实例作为参数传递给它。
User = UserStore.GetUserDetails();
var user = UserStore.GetUserDetails();
User.Fname = user.Fname;
User.Lname = user.Lname;