After some search on web I have set up this simple example:
PropertyChangedBase.cs
public class PropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName) {
//Raise the PropertyChanged event on the UI Thread, with the relevant propertyName parameter:
Application.Current.Dispatcher.BeginInvoke((Action)(() => {
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}));
}
}
UserViewModel.cs
public class UserViewModel : PropertyChangedBase
{
private Visibility _showUserWindow = Visibility.Collapsed;
public Visibility ShowUserWindow {
get { return _showUserWindow; }
set {
_showUserWindow = value;
OnPropertyChanged("ShowUserWindow"); //This is important!!!
}
}
}
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid Margin="43,28,247,129" Background="AliceBlue" Visibility="{Binding ShowUserWindow}"/>
<Button Content="Button" HorizontalAlignment="Left" Margin="349,150,0,0" VerticalAlignment="Top" Width="75" PreviewMouseLeftButtonDown="Button_PreviewMouseLeftButtonDown"/>
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
UserViewModel userViewModel;
public MainWindow() {
InitializeComponent();
userViewModel = new UserViewModel();
DataContext = userViewModel;
}
private void Button_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) {
userViewModel.ShowUserWindow = Visibility.Visible;
Thread.Sleep(1000);
userViewModel.ShowUserWindow = Visibility.Collapsed;
}
}
Right now grid becomes collapsed after 1 sec, I would like to update UI before timer starts. What I am doing wrong?
Edit: Thread.Sleep line immitates some work, that takes some time to complete. Grid should become visible before work starts and show some info about that work and become collapsed after work is done.