Custom Popup control not closing - wpf

I'm trying to create a custom dropdown control that acts like a ComboBox, such that the Popup opens when you click mouse down (not up), and closes when you click outside of the control.
The problem is that it only behaves if I set ClickMode to "Release". But what I really want is ClickMode="Press", such that the Popup opens on MouseDown instead of MouseUp.
But when I set it to ClickMode="Press", the popup won't close when you click outside the control.
Any ideas how I can achieve this?
Usage :
<StackPanel>
<local:CustomDropdown Width="200"
Height="50"
Content="Custom!" />
<ComboBox Width="200"
Margin="20">
<ComboBoxItem>A</ComboBoxItem>
<ComboBoxItem>B</ComboBoxItem>
<ComboBoxItem>C</ComboBoxItem>
</ComboBox>
</StackPanel>
Class :
internal class CustomDropdown : ContentControl
{
public bool IsOpen
{
get { return (bool)GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register("IsOpen", typeof(bool), typeof(CustomDropdown), new PropertyMetadata(false));
}
Xaml :
<Style TargetType="{x:Type local:CustomDropdown}">
<Style.Setters>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid>
<ToggleButton IsChecked="{Binding IsOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
ClickMode="Press"/>
<ContentPresenter Content="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}"
HorizontalAlignment="Center"
VerticalAlignment="Center"/>
<Popup StaysOpen="False"
Placement="Bottom"
IsOpen="{Binding IsOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
<Border Background="White"
BorderBrush="Black"
BorderThickness="1"
Padding="50">
<TextBlock Text="Popup!" />
</Border>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style.Setters>
</Style>

If you want it to work as expected with ClickMode.Press, you should programmatically set the IsOpen property to false whenever you want to the close the Popup. For example whenever you detect a click outside of the ToggleButton.
You could for example handle the PreviewMouseLeftButtonDown event for the parent window in your control. Something like this:
internal class CustomDropdown : ContentControl
{
private ToggleButton _toggleButton;
public CustomDropdown()
{
Loaded += OnLoaded;
Unloaded += OnUnloaded;
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
_toggleButton = GetTemplateChild("toggleButton") as ToggleButton;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
Window window = Window.GetWindow(this);
window.PreviewMouseLeftButtonDown += OnWindowPreviewMouseLeftButtonDown;
}
private void OnUnloaded(object sender, RoutedEventArgs e)
{
Window window = Window.GetWindow(this);
window.PreviewMouseLeftButtonDown -= OnWindowPreviewMouseLeftButtonDown;
}
private void OnWindowPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
ToggleButton toggleButton = FindParent<ToggleButton>(e.OriginalSource as DependencyObject);
if (toggleButton != _toggleButton)
IsOpen = false;
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null)
return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}
public bool IsOpen
{
get { return (bool)GetValue(IsOpenProperty); }
set { SetValue(IsOpenProperty, value); }
}
public static readonly DependencyProperty IsOpenProperty =
DependencyProperty.Register("IsOpen", typeof(bool), typeof(CustomDropdown), new PropertyMetadata(false));
}
}
XAML:
<ControlTemplate>
<Grid>
<ToggleButton x:Name="toggleButton" ...

You already have a working answer. However, finding the parent Window and parent ToggleButton can impact performance (depending on the depth of the visual tree).
As an alternative solution I suggest to focus on handling the Popup instead.
There are two conditions that prevent the Popup from closing itself: the button is configured with the ButtonBase.ClickMode set to ClickMode.Pressed AND the user is not clicking anything focusable inside the Popup.
If one of those two conditions evaluates to false (=> ClickMode.Release or the user has moved focus inside the Popup) your code will work as you would expected it to work.
Note that in order to allow the user to move focus inside the Popup, there must be a child that is focusable (UIElement.Focusable is set to true - it's false by default for most controls that don't require user interaction). For example, TextBlock is not focusable by default.
Because you want to keep the button configured to raise the Click event on mouse button press, you have to move the focus manually. But when you set it manually, the Popup won't receive a mouse click to setup itself to watch the focus. Therefore, you will end up closing the Popup manually (taking away the related control from the Popup).
The following example closes the Popup by observing the Mouse.PreviewMouseDownOutsideCapturedElement event to identify when the focus has moved away from the CustomDropdown control (mouse click outside the Popup):
CustomDropdown.cs
internal class CustomDropdown : ContentControl
{
public bool IsOpen
{
get => (bool)GetValue(IsOpenProperty);
set => SetValue(IsOpenProperty, value);
}
public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register(
"IsOpen",
typeof(bool),
typeof(CustomDropdown),
new PropertyMetadata(default(bool), OnIsOpenChanged));
public CustomDropdown()
{
Mouse.AddPreviewMouseDownOutsideCapturedElementHandler(this, OnPreviewMouseDownOutsideCapturedElement);
}
private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool isOpen = (bool)e.NewValue;
if (isOpen)
{
_ = Mouse.Capture(d as IInputElement, CaptureMode.SubTree);
}
else
{
_ = Mouse.Capture(null);
}
}
// Manually close the Popup if click is recorded outside the CustomDropdown/Popup
private void OnPreviewMouseDownOutsideCapturedElement(object sender, MouseButtonEventArgs e)
{
SetCurrentValue(IsOpenProperty, false);
}
}

Related

WPF closing context menu before open new window

I have a WPF window which use heavy library and takes time to be fully rendered.
This library is in an UserControl.
This window is open by a context menu command in the parent window.
Using MVVM pattern, I need to get the DialogResult of this new window when closing to access the viewmodel.
When clicking the context menu item to open this new window, the context menu stays open until the instanciation of the new window will be done.
What can I do to close the context menu before open this window?
Here is the code refactored with the help of BionicCode:
MAIN WINDOW XAML
<Image Source="{Binding ImagePath}" Height="100" Width="100">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="Open Window"
Command="{x:Static local:MainWindow.ShowMyDialogCommand}"
CommandTarget="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget}"
/>
</ContextMenu>
</Image.ContextMenu>
</Image>
MAIN WINDOW
public partial class MainWindow : Window
{
public static RoutedCommand ShowMyDialogCommand { get; } = new RoutedCommand("ShowMyDialogCommand", typeof(MainWindow));
private readonly MainVM myMainVM;
public MainWindow()
{
InitializeComponent();
myMainVM = new MainVM();
DataContext = myMainVM;
var showMyDialogCommandBinding = new CommandBinding(ShowMyDialogCommand, ExecuteShowMyDialogCommand, CanExecuteShowMyDialogCommand);
this.CommandBindings.Add(showMyDialogCommandBinding);
}
private void CanExecuteShowMyDialogCommand(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
private void ExecuteShowMyDialogCommand(object sender, ExecutedRoutedEventArgs e)
{
ViewerVM vm = new ViewerVM();
var okDialog = new OkDialog()
{
Title = "Viewer Dialog",
DataContext = vm
};
bool? dialogResult = okDialog.ShowDialog();
if (dialogResult == true)
{
this.myMainVM.HandleData(vm);
}
}
}
MAIN VM
public class MainVM : ObservableObject
{
private string myImagePath;
public MainVM()
{
myImagePath = "flower.jpg";
}
public string ImagePath
{
get { return myImagePath; }
set
{
if (myImagePath == value) return;
myImagePath = value;
OnPropertyChanged(nameof(ImagePath));
}
}
public void HandleData(ViewerVM viewModel)
{
//Do stuffs
}
}
NEW WINDOW XAML
<Window.Template>
<ControlTemplate TargetType="Window">
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<!-- Dynamic content row -->
<RowDefinition Height="Auto" />
<!-- Static content row (ok and cancel buttons etc.) -->
</Grid.RowDefinitions>
<!-- Dynamic content -->
<ContentPresenter Grid.Row="0" />
<!-- Static content -->
<StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
<Button Content="Ok" IsDefault="True" Command="{x:Static local:OkDialog.OkCommand}" />
<Button Content="Cancel" IsCancel="True" />
</StackPanel>
</Grid>
</ControlTemplate>
</Window.Template>
NEW WINDOW
public partial class OkDialog : Window
{
public static RoutedCommand OkCommand { get; } = new RoutedCommand("OkCommand", typeof(MainWindow));
public OkDialog()
{
InitializeComponent();
var okCommandBinding = new CommandBinding(OkDialog.OkCommand, ExecuteOkCommand, CanExecuteOkCommand);
this.CommandBindings.Add(okCommandBinding);
this.DataContextChanged += OnDataContextChanged;
}
// If there is no explicit Content set, use the DataContext
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) => this.Content = e.NewValue;
private void CanExecuteOkCommand(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = (this.DataContext as IOkDialogVM).CanExecuteOkCommand() ? true : false;
private void ExecuteOkCommand(object sender, ExecutedRoutedEventArgs e)
=> this.DialogResult = true;
}
interface IOkDialogVM
{
bool CanExecuteOkCommand();
}
UserControl
<UserControl x:Class="ContextMenuTest.Viewer"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ddes="http://schemas.devdept.com/winfx/2008/xaml/control"
xmlns:ddgr="http://schemas.devdept.com/winfx/2008/xaml/graphics"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<ddes:Design x:Name="myDesigner" Height="300" Width="300">
<ddes:Design.Viewports>
<ddes:Viewport>
<ddes:Viewport.Background>
<ddgr:BackgroundSettings StyleMode="Solid" TopColor="White"/>
</ddes:Viewport.Background>
</ddes:Viewport>
</ddes:Design.Viewports>
</ddes:Design>
</Grid>
</UserControl>
public partial class Viewer : UserControl
{
public Viewer()
{
InitializeComponent();
}
}
public class ViewerVM : ObservableObject, IOkDialogVM
{
public bool CanExecuteOkCommand() => true;
}
App.xaml
<Application.Resources>
<DataTemplate DataType="{x:Type local:ViewerVM}">
<local:Viewer/>
</DataTemplate>
</Application.Resources>
Your current code breaks the MVVM design pattern. This is because you are managing views in your View Model. The view model class has no idea that the view will show a dialog. It therefore doesn't participate in any dialog flow.
You control the dialog completely in the View. You show it and you close it without any dependency on a view model class.
When you make use of the Button.IsCancel property the Window will close itself without the need to attach any event handler or close commands to this Button.
Setting the Window.DialogResult will always close the Window and let the Window.ShowDialog return the Window.DialogResult. You only need to attach an event handler to set the Window.DialogResult to true or false.
Window will take care of the rest. It's as easy as it can get. No View Model needed.
To show a dialog in an MVVM application, you can follow the below examples in the sections: MVVM compliant dialog flow and Advanced MVVM compliant dialog flow.
To fix the loading experience, you shouldn't create any views in the constructor. Only do some light work in the constructor so that the constructor can return fast.
As a general rule, you should always avoid creating controls in your code-behind to add them manually to the visual tree. This is done in XAML, which wouldn't cause your current issue in the first place.
If you really need to do it your way, chose to create the views either in the FrameworkElement.Loaded event or override the FrameworkElement.OnApplyTemplate method.
Because of the heavy load, I suggest to move your code to the Loaded event handler.
It's unclear what your DesignView constructor is exactly doing. In case you have shown the complete constructor and the timing of the call of the following line
devDept.LicenseManager.Unlock(typeof(devDept.Eyeshot.Workspace), "mykey");
doesn't matter or can be deferred, you should move this line to the Loaded event handler too. Just in case LicenseManager.Unlock is the blocking piece.
public partial class PartEditView : UserControl
{
private DesignerView myDesignerView;
public PartEditView()
{
InitializeComponent();
// Follow this pattern to unlock the DesignerView.
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
this.myDesignerView = new DesignerView();
this.myDesignerContainer.Children.Add(myDesignerView);
}
}
MVVM compliant dialog flow
The idea is simple, your View is responsible to show the dialog. Data is displayed/collected by binding elements to a dedicated view model of the dialog. After the dialog was closed, the View can interact with the View Model to pass over the data. In most scenarios the view model of the dialog knows how to handle the data (for example how to use the Model to persist data).
MainWindowViewModel.cs
The view model class has no idea that the view will show a dialog.
It doesn't participate in any dialog flow.
If the view model must handle the data collected by a dialog, the responsible view can pass the data to the view model.
class MainWindowViewModel : INotifyPropertyChanged
{
// Such a public method is one possible way to allow the view to pass data
// to this instance. Simply use the common means to send data from View to View Model.
public void HandleData(MyDialogViewModel viewModel)
{
}
}
MainWindow.xaml.cs
partial class MainWindow : Window
{
public static RoutedCommand ShowMyDialogCommand { get; } = new RoutedCommand("ShowMyDialogCommand", typeof(MainWindow));
private MainWindowViewModel MainWindowViewModel { get; }
public MainWindow()
{
InitializeComponent();
this.MainWindowViewModel = new MainWindowViewModel();
this.DataContext = this.MainWindowViewModel;
var showMyDialogCommandBinding = new CommandBinding(ShowMyDialogCommand, ExecuteShowMyDialogCommand, CanExecuteShowMyDialogCommand);
this.CommandBindings.Add(showMyDialogCommandBinding);
}
private void CanExecuteShowMyDialogCommand(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
private void ExecuteShowMyDialogCommand(object sender, ExecutedRoutedEventArgs e)
{
var myDialogViewModel = new MyDialogViewModel();
var myDialog = new MyDialog()
{
Content = "I'm a dialog",
DataContext = myDialogViewModel
};
bool? dialogResult = myDialog.ShowDialog();
// Do something when the user has closed the dialog e.g. using the 'OK' button
if (dialogResult == true)
{
// Pass the dialog data (if it has some) to the view model class
// for further processing. The data is stored via data binding in the
// myDialogViewModel (the DataContext of the dialog).
// Depending on the context of the dialog, the dialog's view model
// knows what to do with the data (e.g. save it to a database using the Model).
this.MainWindowViewModel.HandleDialogData(myDialogViewModel);
}
}
}
MainWindow.xaml
Because the ContextMenu will have its own visual tree (it uses a Popup to display content), the routed command must be executed in the visual tree of the parent Window. For this reason we must explicitly set the MenuItem.CommandTarget property to point to the visual tree outside of the ContextMenu. The CommandTarget will therefore point to the ContextMenu.PlacementTarget (which is the Image in the example). The Image is an element of the Window visual tree where the CommandBinding is defined.
This is only necessary when the routed command is used inside a Popup (for example ContextMenu).
Otherwise setting the CommandTarget is not necessary.
<Window>
<StackPanel>
<!-- CommandTarget is not needed when the ICommandSource is part of the parent Window's visual tree -->
<Button Command="{x:Static local:MainWindow.ShowMyDialogCommand}" />
<Image>
<Image.ContextMenu>
<ContextMenu>
<!-- Visual tree is different from the Window (due to the Popup).
Set CommandTarget to allow the command to traverse the visual tree
of the MainWindow to reach to the CommandBindng (defined by the MainWindow) -->
<MenuItem Header="Open Window"
Command="{x:Static local:MainWindow.ShowMyDialogCommand}"
CommandTarget="{Binding RelativeSource={RelativeSource
AncestorType=ContextMenu}, Path=PlacementTarget}" />
</ContextMenu>
</Image.ContextMenu>
</Image>
</StackPanel>
</Window>
MyDialog.xaml.cs
partial class MyDialog : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OkButton_Click(object sender, RoutedEventArgs e)
{
// Setting the DialogResult will automatically close the Window
// and return the DialogResult value.
this.DialogResult = true;
}
}
MyDialog.xaml
It's important to set Button.IsCancel to true for the "Cancel" button.
This allows the Window to close itself automatically.
Closing the Window in case of the "Ok" button being clicked is achieved by setting the Window.DialogResult property from a Button.Click handler (or RoutedCommand). Window will always close itself when Window.DialogResult is set.
<Window>
<Grid>
<Grid.RowDefinitions>
<RowDefinition /> <!-- Content row -->
<RowDefinition Height="Auto" /> <!-- Dialog button row -->
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Text="I'm a custom dialog" />
<StackPanel Grid.Row="1"
Orientation="Horizontal"
HorizontalAlignment="Right">
<Button Content="Ok"
IsDefault="True"
Click="OkButton_Click"/>
<Button Content="Cancel"
IsCancel="True" />
</StackPanel>
</Grid>
</Window>
Advanced MVVM compliant dialog flow
A more advanced version will make use of the fact that the Window is a ContentControl. This means we can define the content based on a data model (like the above MyDialogViewModel) and load the associated view by defining a DataTemplate, preferably implicit (without the x:Key directive defined). This makes the dialog highly reusable and easy to deal with in an MVVM context.
The following example defines a dialog that only knows how to handle an "Ok" and "Cancel" button. But through data templating the same class can show all kind of views.
IOkDialogViewModel.cs
interface IOkDialogViewModel
{
bool CanExecuteOkCommand();
}
OkDialogViewModel.cs
Example data model that is mapped to a dedicated view via a DataTemplate
that makes the content of the dialog.
// Consider to implement INotifyDataErrorInfo
public class OkDialogViewModel : IOkDialogViewModel, INotifyPropertyChanged
{
public string SomeText { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
public bool CanExecuteOkCommand() => this.SomeText.StartsWith("#");
}
OkDialog.xaml.cs
public partial class OkDialog : Window
{
public static RoutedCommand OkCommand { get; } = new RoutedCommand("OkCommand", typeof(MainWindow));
public OkDialog()
{
InitializeComponent();
var okCommandBinding = new CommandBinding(OkDialog.OkCommand, ExecuteOkCommand, CanExecuteOkCommand);
this.CommandBindings.Add(okCommandBinding);
this.DataContextChanged += OnDataContextChanged;
}
// If there is no explicit Content set, use the DataContext
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) => this.Content ??= e.NewValue;
private void CanExecuteOkCommand(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = (this.DataContext as IOkDialogViewModel)?.CanExecuteOkCommand() ?? true;
private void ExecuteOkCommand(object sender, ExecutedRoutedEventArgs e)
=> this.DialogResult = true;
}
OkDialog.xaml
Now hardcode the default content (the "Ok" and "Close" buttons) into the Window.Template. This will make the static content.
The dynamic content is implicitly created by the client who defined a DataTemplate for the Window.Content.
<Window>
<Window.Template>
<ControlTemplate TargetType="Window">
<Grid>
<Grid.RowDefinitions>
<RowDefinition /> <!-- Dynamic content row -->
<RowDefinition Height="Auto" /> <!-- Static content row (ok and cancel buttons etc.) -->
</Grid.RowDefinitions>
<!-- Dynamic content -->
<ContentPresenter Grid.Row="0" />
<!-- Static content -->
<StackPanel Grid.Row="1"
Orientation="Horizontal"
HorizontalAlignment="Right">
<Button Content="Ok"
IsDefault="True"
Command="{x:Static local:OkDialog.OkCommand}" />
<Button Content="Cancel"
IsCancel="True" />
</StackPanel>
</Grid>
</ControlTemplate>
</Window.Template>
</Window>
App.xaml
Define a DataTemplate to crate the particular dialog view that is associated with the OkDialogViewModel.
<Application>
<Application.Resources>
<DataTemplate DataType="{x:Type local:OkDialogViewModel}">
<TextBox Text="{Binding SomeText}" />
</DataTemplate>
</Application.Resources>
</Application>
MainWindow.xaml.cs
partial class MainWindow : Window
{
public static RoutedCommand ShowMyDialogCommand { get; } = new RoutedCommand("ShowMyDialogCommand", typeof(MainWindow));
private MainWindowViewModel MainWindowViewModel { get; }
public MainWindow()
{
InitializeComponent();
this.MainWindowViewModel = new MainWindowViewModel();
this.DataContext = this.MainWindowViewModel;
var showMyDialogCommandBinding = new CommandBinding(ShowMyDialogCommand, ExecuteShowMyDialogCommand, CanExecuteShowMyDialogCommand);
this.CommandBindings.Add(showMyDialogCommandBinding);
}
private void CanExecuteShowMyDialogCommand(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = true;
private void ExecuteShowMyDialogCommand(object sender, ExecutedRoutedEventArgs e)
{
// Because the text doesn't start with '#', the OK button will be disabled later,
// until the user fixes the input in the TextBox.
var dialogViewModel = new OkDialogViewModel() { SomeText = "Just some text" };
var okDialog = new OkDialog()
{
Title = "I'm an Ok dialog",
DataContext = dialogViewModel
};
bool? dialogResult = okDialog.ShowDialog();
// Do something when the user has closed the dialog e.g. using the 'OK' button
if (dialogResult == true)
{
// Pass the dialog data (if it has some) to the view model class
// for further processing. The data is stored via data binding in the
// DataContext/Content of the dialog.
// Depending on the context of the dialog, the dialog's view model
// knows what to do with the data (e.g. save it to a database using the Model).
this.MainWindowViewModel.HandleData(dialogViewModel);
}
}
}
MainWindow.xaml
Because the ContextMenu will have its own visual tree (it uses a Popup to display content), the routed command must be executed in the visual tree of the parent Window. For this reason we must explicitly set the MenuItem.CommandTarget property to point to the visual tree outside of the ContextMenu. The CommandTarget will therefore point to the ContextMenu.PlacementTarget (which is the Image in the example). The Image is an element of the Window visual tree where the CommandBinding is defined.
This is only necessary when the routed command is used inside a Popup (for example ContextMenu).
Otherwise setting the CommandTarget is not necessary.
<Window>
<StackPanel>
<!-- CommandTarget is not needed when the ICommandSource is part of the parent Window's visual tree -->
<Button Command="{x:Static local:MainWindow.ShowMyDialogCommand}" />
<Image>
<Image.ContextMenu>
<ContextMenu>
<!-- Visual tree is different from the Window (due to the Popup).
Set CommandTarget to allow the command to traverse the visual tree
of the MainWindow to reach to the CommandBindng (defined by the MainWindow) -->
<MenuItem Header="Open Window"
Command="{x:Static local:MainWindow.ShowMyDialogCommand}"
CommandTarget="{Binding RelativeSource={RelativeSource
AncestorType=ContextMenu}, Path=PlacementTarget}" />
</ContextMenu>
</Image.ContextMenu>
</Image>
</StackPanel>
</Window>
Update
It turns out that the origin is really the 3rd party library. The implementation of the control is obviously really bad. It freezes the UI during construction/loading which is unacceptable.
Because the UI is frozen you can't even show a busy indicator. The user is left to believe that the application has crashed.
Such a library would make me doubt the authors skills and experience.
Because of the serious impact on the application's performance and UX I recommend to find an alternative library.
Even closing the ContextMenu forcefully does not solve the problem of a bad UX as the application still hangs.
The following solution extends the previous "Advanced MVVM compliant dialog flow" example. Following the "Advanced MVVM compliant dialog flow" will give you a clean design that helps to solve the issue more "gracefully" (I still recommend to find a better library).
The solution implements the following flow:
Instead of opening the dialog (which contains the terrible control) directly on clicking the MenuItem, we modify the flow to first close the ContextMenu.
This is accomplished by registering a ContextMenu.Opened event handler.
Next we spawn a second UI thread. Because any busy indicator that runs in the primary UI thread would freeze too, we use this dedicated new UI thread to show a busy indicator dialog. This way we can improve the UX significantly as from the user's point of view everything appears to be under control: just some heavy loading in the background.
In the main UI tread we create the instance of the dialog which is known to freeze the application (which will still freeze)
We use a SemaphoreSlim to allow the busy indicator dialog to wait asynchronously for a signal from the main UI thread in order to continue.
After the busy indicator thread received the signal, the busy indicator will close itself and shut down the second UI thread
The dialog cantaining the 3rd party control is now ready to use.
MainWindow.xaml
<Window>
<Image>
<Image.ContextMenu>
<ContextMenu Closed="OnImageContextMenuClosed">
<!-- Visual tree is different from the Window (due to the Popup).
Set CommandTarget to allow the command to traverse the visual tree
of the MainWindow to reach to the CommandBindng (defined by the MainWindow) -->
<MenuItem Header="Open Window"
Command="{x:Static local:MainWindow.ShowMyDialogCommand}"
CommandTarget="{Binding RelativeSource={RelativeSource
AncestorType=ContextMenu}, Path=PlacementTarget}" />
</ContextMenu>
</Image.ContextMenu>
</Image>
</Window>
MainWindow.xaml.cs
partial class MainWindow : Window
{
public static RoutedCommand ShowMyDialogCommand { get; } = new RoutedCommand("ShowMyDialogCommand", typeof(MainWindow));
private MainWindowViewModel MainWindowViewModel { get; }
public MainWindow()
{
InitializeComponent();
this.MainWindowViewModel = new MainWindowViewModel();
this.DataContext = this.MainWindowViewModel;
var showMyDialogCommandBinding = new CommandBinding(ShowMyDialogCommand, ExecuteShowMyDialogCommand, CanExecuteShowMyDialogCommand);
this.CommandBindings.Add(showMyDialogCommandBinding);
}
private void CanExecuteShowMyDialogCommand(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = true;
// Only close the ContextMenu. The ContextMenu.Closed event will continue the flow.
private void ExecuteShowMyDialogCommand(object sender, ExecutedRoutedEventArgs e)
=> (e.OriginalSource as FrameworkElement).ContextMenu.IsOpen = false;
private void OnImageContextMenuClosed(object? sender, EventArgs e)
{
// Create a semaphore that is initially blocking.
// The semaphore is used to signal the new UI thread that it must shut down
// and close the busy indicator dialog.
using var semaphore = new SemaphoreSlim(0, 1);
var uiThread = new Thread(state => ShowBusyIndicator(semaphore))
{
IsBackground = false
};
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
(bool IsOk, OkDialogViewModel ViewModel) dialogResult = ShowOkDialog(semaphore);
// Do something when the user has closed the dialog e.g. using the 'OK' button
if (dialogResult.IsOk)
{
//dialogResult.ViewModel
}
}
private void ShowBusyIndicator(SemaphoreSlim semaphore)
{
// Consider to create a dedicated BusyIndicatorDialog class (following the pattern of the OkDialog).
// This allows to create a DataTemplate to design the dialog using XAML.
var busyIndicator = new Window()
{
Content = new ProgressBar() { IsIndeterminate = true },
Title = "Loading, please wait..."
};
// Let the busy indicator dialog wait for the SemaphoreSlim to signal.
// Consider to move this code directly to a dedicated BusyIndicatorDialog class.
// In case of implementing a dedicated BusyIndicatorDialog, consider to implement a special event which allows more control over the timing of the event (to replace the Loaded event).
busyIndicator.Loaded += (s, e) => OnBusyIndicatorLoaded(busyIndicator, semaphore);
busyIndicator.Show();
Dispatcher.Run();
}
// Use the Dispatcher of the busy indicator Window to post the code to the second UI thread.
private void OnBusyIndicatorLoaded(Window busyIndicator, SemaphoreSlim semaphore)
{
_ = busyIndicator.Dispatcher.InvokeAsync(async () =>
{
// Wait for the signal to continue the thread.
await semaphore.WaitAsync();
busyIndicator.Close();
busyIndicator.Dispatcher.BeginInvokeShutdown(DispatcherPriority.ContextIdle);
}, DispatcherPriority.ContextIdle);
}
private (bool IsOk, OkDialogViewModel ViewModel) ShowOkDialog(SemaphoreSlim semaphore)
{
var dialogViewModel = new OkDialogViewModel() { SomeText = "Just some text" };
var myDialog = new OkDialog()
{
Title = "I'm a Ok dialog",
DataContext = dialogViewModel
};
// Signal the busy indicator thread to continue (it will close itself and shut down the thread)
_ = semaphore.Release();
bool dialogResult = myDialog.ShowDialog() ?? false;
return (dialogResult, dialogViewModel);
}
}

how wpf binding a event in ControlTemplate

Code behind:
public class LoginButton : Button
{
public static DependencyProperty LoginedProperty;
public static DependencyProperty LoginEventProperty;
public delegate void LoginEventDelegate(object sender, RoutedEventArgs e);
static LoginButton()
{
LoginedProperty = DependencyProperty.Register("Logined", typeof(Boolean), typeof(LoginButton));
LoginEventProperty = DependencyProperty.Register("LoginEvent", typeof(LoginEventDelegate), typeof(LoginButton));
}
public Boolean Logined
{
get { return (Boolean)base.GetValue(LoginedProperty); }
set { base.SetValue(LoginedProperty, value); }
}
public event LoginEventDelegate LoginEvent;
protected virtual void OnLoginEvent(object sender, RoutedEventArgs e)
{
if (LoginEvent != null)
LoginEvent(sender,e);
}
}
XAML:
<ControlTemplate x:Key="LoginButtonTemplate" TargetType="local:LoginButton">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<ContentPresenter VerticalAlignment="Center" Margin="10,0,0,0"></ContentPresenter>
<Grid Grid.Column="1" Margin="5,0,0,0">
<Label Name="L" VerticalAlignment="Center" Padding="0" Foreground="#919191" Visibility="Collapsed">logined</Label>
<Button Name="B" Template="{StaticResource CustomButton}" Background="Transparent" BorderThickness="0" Padding="0" Foreground="#3598db" Content="click login"></Button>
</Grid>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="Logined" Value="true">
<Setter TargetName="L" Property="Visibility" Value="Visible"></Setter>
<Setter TargetName="B" Property="Visibility" Value="Collapsed"></Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
--------------------------------
I want to achieve this function:
The button which Name="B" in ControlTemplate,when I click it,it work the custom event OnLoginEvent?
How can i do it?
--------------------------------
Oh,it seems no one knows my meaning for my poor English.
Now I explain the function for more detailed.
The software needs to manage about 100 or more account,if the account is not logined,it will show the button let user to login.And if is logined it will show the label that is logined
So I make a new Custom usercontrol named LoginButton,and create a boolean 'Logined' to control button if is logined.
Beaucase of different account has different login function.So I create a new event 'LoginEvent' to apply different login function.Now the question is the button Name="B" which to login.I need binding the button Name="B" click event or previewmousedown event to the event 'LoginEvent'.But I can't find the way to binding it.
Please help me,thanks a lot.
You could override the OnApplyTemplate method of the LoginButton class and hook up an event handler to the click event for the "B" button in the template that raises the event.
LoginEvent should be an event and not a dependency property though.
Try this:
public class LoginButton : Button
{
public static DependencyProperty LoginedProperty;
public delegate void LoginEventDelegate(object sender, RoutedEventArgs e);
static LoginButton()
{
LoginedProperty = DependencyProperty.Register("Logined", typeof(Boolean), typeof(LoginButton));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
Button b = this.Template.FindName("B", this) as Button;
if(b != null)
{
b.Click += (s, e) => OnLoginEvent(s, e);
}
}
public Boolean Logined
{
get { return (Boolean)base.GetValue(LoginedProperty); }
set { base.SetValue(LoginedProperty, value); }
}
public event LoginEventDelegate LoginEvent;
protected virtual void OnLoginEvent(object sender, RoutedEventArgs e)
{
if (LoginEvent != null)
LoginEvent(sender, e);
}
}
Usage:
<local:LoginButton Template="{StaticResource LoginButtonTemplate}" LoginEvent="LoginButton_LoginEvent"/>
private void LoginButton_LoginEvent(object sender, RoutedEventArgs e)
{
MessageBox.Show("Login!");
}

How can I bind a behavior in a style using an element name from another property

I want to bind a focus behavior to a reset button that will put the focus on the control named in the ElementToFocus property
<Style TargetType="Button" x:Key="Button_Reset" BasedOn="{StaticResource Button_Default}" >
<Setter Property="ElementToFocus" />
<Setter Property="behaviors:EventFocusAttachment.ElementToFocus" Value="{Binding ElementName=ElementToFocus}" />
</Style>
Control Markup:
<Button
x:Name="button_Clear"
Style="{DynamicResource Button_Reset}"
HorizontalAlignment="Right"
Content="Clear"
Command="{Binding Path=ClearCommand}"
ElementToFocus="textbox_SearchText"
Margin="0,0,0,7" />
How can I accomplish this?
I have created an attached behavior to try and achieve what you are trying to do.
Attached Behavior Code:
public static class ElementFocusBehavior
{
public static readonly DependencyProperty ElementToFocusProperty =
DependencyProperty.RegisterAttached("ElementToFocus", typeof (FrameworkElement), typeof (ElementFocusBehavior), new PropertyMetadata(default(FrameworkElement), PropertyChangedCallback));
private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
{
var button = dependencyObject as Button;
if (button == null) return;
if (button.IsLoaded)
{
AddClickHandler(button);
}
else
{
button.Loaded += ButtonOnLoaded;
}
}
private static void ButtonOnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
var button = (Button) sender;
button.Loaded -= ButtonOnLoaded;
AddClickHandler(button);
}
static void AddClickHandler(Button button)
{
button.Click += ButtonOnClick;
}
private static void ButtonOnClick(object sender, RoutedEventArgs routedEventArgs)
{
var fe = GetElementToFocus(sender as Button) as FrameworkElement;
if (fe == null) return;
fe.Focus();
}
public static void SetElementToFocus(Button button, FrameworkElement value)
{
button.SetValue(ElementToFocusProperty, value);
}
public static FrameworkElement GetElementToFocus(Button button)
{
return (FrameworkElement) button.GetValue(ElementToFocusProperty);
}
}
And the XAML for Button:
<Button Content="Reset" local:ElementFocusBehavior.ElementToFocus="{Binding ElementName=TextBoxThree, Path=.}" />
Sample code from my MainWindow:
<StackPanel>
<TextBox Name="TextBoxOne" />
<TextBox Name="TextBoxTwo" />
<TextBox Name="TextBoxThree" />
<Button Content="Reset" local:ElementFocusBehavior.ElementToFocus="{Binding ElementName=TextBoxThree, Path=.}" />
</StackPanel>
Basically, what I did was,
have an attached behavior to store the element to be focused,
and then in the attached behavior add event handler to button Click event,
in the Click event set the Focus on the ElementToFocus element
Hope this helps.

how to show messagebox when wpf app closing?

I have a WPF app with MVVM pattern and it contains following 2 views:
1:MainWindow.xaml (it's a window)
below is main portion of MainWindow.xaml:
<Window.Resources>
<DataTemplate DataType="{x:Type vm:XliffListViewModel}">
<vw:XliffListView />
</DataTemplate>
</Window.Resources>
<Grid Margin="4">
<Border Background="GhostWhite" BorderBrush="LightGray" BorderThickness="1" CornerRadius="5" >
<ItemsControl ItemsSource="{Binding ViewModels}" Margin="4" />
</Border>
</Grid>
2:XliffListView.xaml (it's a user control)
XliffListView contain a datagrid and a button for save all changes that happens
I want to show messagebox when user closing app if changes not saved
You can write and Attached behavior that handles Window.Closing() event of the Window and executes the ClosingCommand from ViewModel and returns true or false as parameter so that one can cancel (e.Cancel) closing event if the VM wants to stop th window from closing.
The code below is just for concept and is not complete
XAML
<Window x:Class="..."
...
myBheaviors:WindowBehaviors.ClosingCommand="{Binding MyClosingCommand}">
...
</Window>
ViewModel
public class MyWindowViewModel
{
public ICommand MyClosingCommand
{
get
{
if (_myClosingCommand == null)
_myClosingCommand
= new DelegateCommand<CancelEventArgs>(OnClosing);
return _myClosingCommand;
}
}
private void OnClosing(CancelEventArgs e)
{
if (this.Dirty) //Some function that decides if the VM has pending changes.
e.Cancel = true;
}
}
Attached Behavior
public static class WindowBehaviors
{
public static readonly DependencyProperty ClosingCommandProperty
= DependencyProperty.RegistsrrAttached(
"ClosingCommand",
...,
new PropertyMetataData(OnClosingCommandChanged);
public static ICommand GetClosingCommand(...) { .. };
public static void SetClosingCommand(...) { .. };
private static void OnClosingCommandChanged(sender, e)
{
var window = sender as Window;
var command = e.NewValue as ICommand;
if (window != null && command != null)
{
window.Closing
+= (o, args) =>
{
command.Execute(args);
if (args.Cancel)
{
MessageBox.Show(
"Window has pending changes. Cannot close");
// Now window will be stopped from closing.
}
};
}
}
}
EDIT:
For user controls, instead of Closing use Unloaded event.
Also try to establish a hierarchy between ViewModels i.e.e Window's ViewModel should contain UserControl's ViewModel. So that Closing event's IsDirty() call can scrutinize the UserControls' ViewModel also.

Enable a child control when the parent is disabled

I have a Button containing a Hyperlink, like so:
<Button IsEnabled="False">
<Hyperlink IsEnabled="True">Testing</Hyperlink>
</Button>
I need the Hyperlink to be enabled, however the Button to be disabled. How can I achieve this?
The above simply results in both controls being disabled.
I solved this problem by creating a simple wrapper element that breaks the IsEnabled inheritance chain from the parent.
The framework's default coerce callback checks the parent IsEnabled value and inherits it. This control sets a new coerce callback that just returns the value directly without checking inheritance.
public class ResetIsEnabled : ContentControl
{
static ResetIsEnabled()
{
IsEnabledProperty.OverrideMetadata(
typeof(ResetIsEnabled),
new UIPropertyMetadata(
defaultValue: true,
propertyChangedCallback: (_, __) => { },
coerceValueCallback: (_, x) => x));
}
}
In the example from the question it would be used like this:
<Button IsEnabled="False">
<ResetIsEnabled>
<!-- Child elements within ResetIsEnabled have IsEnabled set to true (the default value) -->
<Hyperlink>Testing</Hyperlink>
</ResetIsEnabled>
</Button>
Control Hyperlink has strangely with the property IsEnabled. In addition to the one that you mentioned, namely, the full value inheritance from a parent, there is another similar.
Hyperlink for the specific control, which has been turned off (IsEnabled="False"), setting (IsEnabled="True") will not update the Hyperlink property. The solution - use a relative source for Hyperlink (more info).
For solving your question, I have decided that it is not the standard way to solve. So I created a Class with its own dependencies properties. It has it's property MyIsEnabled and MyStyle. As you might guess from the title, the first sets its property IsEnabled and MyStyle need to specify the button style, simulating the IsEnabled="False" behavior.
SimulateDisable Style
<Style x:Key="SimulateDisable" TargetType="{x:Type Button}">
<Setter Property="Opacity" Value="0.5" />
<Setter Property="Background" Value="Gainsboro" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border CornerRadius="4" BorderThickness="1" BorderBrush="DarkBlue" SnapsToDevicePixels="True">
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Define Button with yours properties:
<Button Name="MyButton" local:MyClass.MyIsEnabled="False" local:MyClass.MyStyle="{StaticResource SimulateDisable}" Width="100" Height="30" Click="Button_Click">
<Hyperlink IsEnabled="True" Click="Hyperlink_Click">Testing</Hyperlink>
</Button>
Listing of MyClass
public class MyClass : DependencyObject
{
public static readonly DependencyProperty MyIsEnabledProperty;
public static readonly DependencyProperty MyStyleProperty;
#region MyIsEnabled
public static void SetMyIsEnabled(DependencyObject DepObject, bool value)
{
DepObject.SetValue(MyIsEnabledProperty, value);
}
public static bool GetMyIsEnabled(DependencyObject DepObject)
{
return (bool)DepObject.GetValue(MyIsEnabledProperty);
}
#endregion MyIsEnabled
#region MyStyle
public static void SetMyStyle(DependencyObject DepObject, Style value)
{
DepObject.SetValue(MyStyleProperty, value);
}
public static Style GetMyStyle(DependencyObject DepObject)
{
return (Style)DepObject.GetValue(MyStyleProperty);
}
#endregion MyStyle
static MyClass()
{
MyIsEnabledProperty = DependencyProperty.RegisterAttached("MyIsEnabled",
typeof(bool),
typeof(MyClass),
new UIPropertyMetadata(false, OnPropertyChanged));
MyStyleProperty = DependencyProperty.RegisterAttached("MyStyle",
typeof(Style),
typeof(MyClass),
new UIPropertyMetadata(OnPropertyChanged));
}
private static void OnPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
Button MyButton = sender as Button;
bool MyBool = GetMyIsEnabled(MyButton);
if (MyBool == false)
{
MyButton.Style = MyClass.GetMyStyle(MyButton);
}
}
}
Plus for the event Hyperlink pointing e.Handled = true, so that the event did not happen next.
private void Hyperlink_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hyperlink Click!");
e.Handled = true;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Button Click! Don't show it's!");
}
Output
P.S. Sorry for late answer :).

Resources