gpt4 book ai didi

xaml - UWP 绑定(bind)到属性

转载 作者:行者123 更新时间:2023-12-04 17:51:28 27 4
gpt4 key购买 nike

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

这是我的 View 模型:

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 构造函数本身中初始化 View 模型时,绑定(bind)工作正常:

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

最佳答案

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

不过你可以简单地替换

User = UserStore.GetUserDetails();

通过

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

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

关于xaml - UWP 绑定(bind)到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44406202/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com