我的应用程序中有两个Usercontrol,一个是Mainwindow,另一个是LoginWindow。 Mainwindow.xaml中的标签绑定到" UserName"应该从LoginWindow更新。
MainWindow.Xaml
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Label Content="UserName: " FontWeight="Bold"/>
<Label Content="{Binding UserName}"/>
</StackPanel>
<Button Width="200" Height="30" VerticalAlignment="Bottom" Content="Open Login Window" Click="Button_Click" />
</StackPanel>
</Grid>
Mainwindow.xaml.cs 显示在登录窗口
private void Button_Click(object sender, RoutedEventArgs e)
{
LoginWindow loginwin = new LoginWindow();
var host = new Window();
host.Content = loginwin;
host.Show();
}
成功登录后,UserName将显示在Mainwindow上。
在LoginWindow中,我只是放了一个按钮,触发UserName更新到Mainwindow。
LoginWindow.xaml.cs
private LoginClass UserObj { get; set; }
private void Login_click(object sender, RoutedEventArgs e)
{
UserObj = new LoginClass { Username = "From LoginWindow" };
// How can i update the control <label content > in another userrcontrol
}
实现INotifyPropertyChnaged事件的LoginClass.cs
private string _username;
public string Username
{
get { return _username; }
set
{
_username = value;
onPropertyChnaged("Username");
}
}
private void onPropertyChnaged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
如果我从Mainwindow提出用户名,并将Datacontext提供给LoginClass的对象,则程序正在按预期工作。
当我从Mainwindow itslef更改属性时,MainWindow上的UI正在更新。
private LoginClass UserObj { get; set; }
private void Button_click(object sender, RoutedEventArgs e)
{
UserObj = new LoginClass { Username = "From MainWindow" };
this.DataContext = UserObj;
// INotifyPropertyChanged implementation is working fine as i am giving datacontext to UserObj to get updated
}
如何使用Inotifypropertychnaged事件从另一个窗口更新UI。
我在过去4个小时内尝试这个..请求帮助。
非常感谢!
答案 0 :(得分:1)
两个窗口应使用相同的DataContext
,即您只应创建LoginClass
的单个实例:
<强>主窗口:强>
public partial class MainWindow : Window, INotifyPropertyChanged
{
LoginClass UserObj = new LoginClass { Username = "From MainWindow" };
public MainWindow()
{
InitializeComponent();
DataContext = UserObj;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LoginWindow loginwin = new LoginWindow();
loginWin.DataContext = UserObj;
var host = new Window();
host.Content = loginwin;
host.Show();
}
}
<强>登录窗口:强>
private void Login_click(object sender, RoutedEventArgs e)
{
var viewModel = DataContext as LoginClass;
viewModel.Username = "From LoginWindow"
}