UWP绑定到属性

拉维·库马尔

我正在制作UWP,但无法正确掌握DataBindingINotifyPropertyChanged我正在尝试将其中的一些绑定到我的代码隐藏cs文件TextBox中的ContentDialog属性。

这是我的视图模型:

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();
    }
}

这是XAML ContentDialog

<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" };
克莱门斯

User用新的视图模型实例替换属性的值时,不会触发PropertyChanged事件

但是,您可以简单地替换

User = UserStore.GetUserDetails();

通过

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

从而更新视图模型现有实例

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章