My main goal here is to add an overlay when my dialog is shown. The approach that I took is to have a bool to visibility converter that determines the visibility state of a Border
which acts as an overlay.
This is the overlay for the MainWindow:
<!--MainWindow.xaml-->
<!--The MainWindow overlay-->
<Border VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Background="#000000"
Opacity="0.5"
CornerRadius="20"
Visibility="{Binding MainWindowOverlay,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged,
FallbackValue=Collapsed,
Converter={StaticResource BooleanToVisibilityConverter }}"/>
This is the bool to visibility converter (in App.xaml)
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
I added a static property
in my MainWindowViewModel that will be used to bind for my overlay
, so that I can access it whenever I want a dialog to be shown (by ShowDialog())
public static bool MainWindowOverlay { get; set; }
I know that the value MainWindowOverlay
is changing because I tested it (in another ViewModel ProjectsViewModel
)
//A method supplied in a delegate command
public void ShowAddProjectsDialog()
{
//This prints false (since false is the default value)
MessageBox.Show(MainWindowViewModel.MainWindowOverlay.ToString());
MainWindowViewModel.MainWindowOverlay = true;
//Now this prints true, but the overlay in my main UI (MainWindow) does not update it
MessageBox.Show(MainWindowViewModel.MainWindowOverlay.ToString());
//This dialog is displayed, but the overlay is not applied to the MainWindow
AddProjectModalDialog addProjectModalDialog = new AddProjectModalDialog();
addProjectModalDialog.ShowDialog();
}
This is how I implement my BaseViewModel
// I am using PropertyChanged.Fody (nuget package) to add a "PropertyChanged" to all my Properties which notifies me when a change happens
[AddINotifyPropertyChangedInterface]
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = (sender, e) => { };
}
Edit (Final output, solved):
MainWindow.xaml
<!--The MainWindow overlay-->
<Border VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Background="#000000"
Opacity="0.3"
CornerRadius="20"
Visibility="{Binding Path=(windowViewModel:MainWindowViewModel.Overlay),
FallbackValue=Collapsed,
Converter={StaticResource BooleanToVisibilityConverter }}" />
MainWindowViewModel.cs
//Event handler for static property (MainWindowOverlay), since PropertyChanged.Fody (nuget package) doesn't notify static property changes
//The static property name in this ViewModel is Overlay. The event name is therefore OverlayChanged (or else it will not notify the changes)
public static event EventHandler OverlayChanged;
public static bool Overlay //The data bound property in MainWindow
{
get { return _overlay; }
set
{
_overlay = value;
if (OverlayChanged is not null)
OverlayChanged(null, EventArgs.Empty);
}
}