UWP绑定到一个属性

时间:2017-06-07 07:28:16

标签: xaml data-binding uwp inotifypropertychanged

我正在制作UWP并且无法正确掌握DataBindingINotifyPropertyChanged 我试图将TextBox中的一些ContentDialog绑定到我的代码隐藏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" };

2 个答案:

答案 0 :(得分:1)

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

然而,您可以简单地替换

User = UserStore.GetUserDetails();

通过

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

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

答案 1 :(得分:0)

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

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

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