我有2个UserControls的小型应用程序。第一个包含登录表单,第二个包含UserControl显示的已验证用户。但是在第二个用户控件中,我无法显示AuthenticatedUser。我viewmodel是AuthenticatedUser的值,但不是在xaml中。 这是我的代码:
MainWindow.xaml
<local:Login/>
<local:Test/>
Login.xaml
<TextBox Text="{Binding Username, UpdateSourceTrigger=LostFocus}"/>
<Button Content="LOGIN" Command="{Binding LoginCommand}"/>
AFTER LOGIN BUTTON CLICK HERE IS VALUE
<TextBlock Text="{Binding AuthenticatedUser}"/>
LoginVM.cs
class LoginVM : BaseVm
{
private string _username;
public string Username
{
get => _username;
set
{
_username = value;
OnPropertyChanged(nameof(Username));
}
}
public Command LoginCommand { get; }
public LoginVM()
{
LoginCommand = new Command(x =>
{
var principal = Thread.CurrentPrincipal as Principal;
principal.Identity = new Identity(Username);
OnPropertyChanged(nameof(AuthenticatedUser));
});
}
}
BaseVM
class BaseVm : INotifyPropertyChanged
{
public string AuthenticatedUser => (Thread.CurrentPrincipal as Principal).Identity.Name;
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Test.xaml
<TextBlock Text="USER: "/>
AFTER LOGIN BUTTON CLICK HERE IS NOT VALUE
<TextBlock Text="{Binding AuthenticatedUser}"/>
TestVm.cs
class TestVm : BaseVm
{
}
如何通知其他userControl?感谢您的建议