UWP 绑定到 属性

UWP Binding to a property

我正在制作UWP,无法正确掌握DataBindingINotifyPropertyChanged 我正在尝试将 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>

注意:当我在 MainPage 构造函数本身中初始化视图模型时,绑定工作正常,如下所示:

User = new UserViewModel { Fname = "name", Lname = "name" };

您应该将 DataContext 属性 设置为视图模型实例:

public MainPage()
{
    this.InitializeComponent();     
    User = new UserViewModel();
    DataContext = User;
}

参见:https://docs.microsoft.com/en-us/windows/uwp/data-binding/data-binding-in-depth

当您将 User 属性 的值替换为新的视图模型实例时,不会触发 PropertyChanged 事件。

但是您可以简单地替换

User = UserStore.GetUserDetails();

来自

var user = UserStore.GetUserDetails();
User.Fname = user.Fname;
User.Lname = user.Lname;

并因此更新视图模型的现有实例