I am trying to disable the close button on a window via MVVM
I realise that you can do this in the view (window) CS code by stating
public Window()
{
InitializeComponent();
this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);
}
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
However I would like to keep it consistent and try to do this is the MVVM.
Thanks
It's a strange demand. If you have a closing button,why you disable it's func. But you can realize it with mvvm like this:
add two ref:
- Microsoft.Expression.Interactions.dll
- System.Windows.Interactivity.dll
add two xmlns:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
create trigger to window:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
Title="MainWindow" Height="350" Width="525">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<ei:CallMethodAction TargetObject="{Binding}" MethodName="WindowsClosing"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<Grid >
</Grid>
</Window>
edit viewmodel,and creat closing func:
public void WindowsClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
}
Change your Closing method with a variable from ViewModel.
void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = (this.DataContext as MyViewModel).ProcessWorking;
}
In your ViewModel (MyViewModel) add a property ProcessWorking :
public Boolean ProcessWorking
{
get { return this.processWorking; }
}
and in your method of background thread, just modify processWorking
private Boolean processWorking;
private void MyBackgroundThread()
{
this.processWorking = true;
// do your process
this.processWorking = false;
}
You can add a RaisePropertyChange() when you modify this.processWorking if you want to show somewhere of your UI the state of the background process.
you can use the ResizeMode of Window or you can use it by using Window API use of Window API mentioend Here
Related
I have a fairly simple C# WPF application using .NET 5. Basically it sits in the background and times specific events for the end user. The events are built from a xml file that is generated externally.
The application consists of 2 windows, one hidden that does all the thinking. If it detects that an event is due it raises a toast message which when clicked on opens the other window to show the event details to the user. All works fine and runs as expected except after a windows sleep/suspend and resume. We obviously don't want the events to add up upon sleep/suspend and so we close the hidden window and upon resume open it again. No problems there but once the system is resumed and an event is raised the visible window refuses to show. If the visible window is open when sleep/suspend happens then upon resume the whole window is frozen and refuses to respond (only way to close the window is kill the application and restart)
The APP code is as follows :-
public static Forms.NotifyIcon notifyIcon;
public static MainWindow mw;
public static ConfigWindow cw;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(SystemEvents_PowerModeChanged);
// Listen to notification activation
ToastNotificationManagerCompat.OnActivated += toastArgs =>
{
// Obtain the arguments from the notification
ToastArguments args = ToastArguments.Parse(toastArgs.Argument);
// Obtain any user input (text boxes, menu selections) from the notification
ValueSet userInput = toastArgs.UserInput;
// Need to dispatch to UI thread if performing UI operations
Application.Current.Dispatcher.Invoke(delegate
{
ToastControl.HandleToast(args);
});
};
ConfNotifyIcon();
OpenApp();
}
private void ConfNotifyIcon()
{
notifyIcon = new Forms.NotifyIcon();
notifyIcon.Icon = new System.Drawing.Icon("Images/Wellformation.ico");
notifyIcon.DoubleClick += OnClick;
notifyIcon.ContextMenuStrip = new Forms.ContextMenuStrip();
notifyIcon.ContextMenuStrip.Items.Add("Open", System.Drawing.Image.FromFile("Images/Wellformation.ico"), OnClick);
notifyIcon.ContextMenuStrip.Items.Add("Close", System.Drawing.Image.FromFile("Images/Wellformation.ico"), OnClose);
notifyIcon.ContextMenuStrip.Items.Add(new Forms.ToolStripSeparator());
notifyIcon.ContextMenuStrip.Items.Add("Exit", System.Drawing.Image.FromFile("Images/Wellformation.ico"), OnExit);
}
private void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
switch (e.Mode)
{
case PowerModes.Suspend:
this.Dispatcher.BeginInvoke((Action)(() =>
{
PrepareLock();
}), null);
break;
case PowerModes.Resume:
this.Dispatcher.BeginInvoke((Action)(() =>
{
PrepareAwake();
}), null);
break;
default:
break;
}
}
private void PrepareAwake()
{
OpenApp();
ConfNotifyIcon();
notifyIcon.Visible = true;
}
private void PrepareLock()
{
notifyIcon.Dispose();
cw.Close();
}
private void OnExit(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
private void OnClose(object sender, EventArgs e)
{
mw.Close();
}
private void OnClick(object sender, EventArgs e)
{
OpenMain();
}
private void OpenMain()
{
mw = new();
mw.Show();
mw.Activate();
}
public static void OpenApp()
{
cw = new ConfigWindow();
}
The hidden Window XAML is as follows :-
<Window x:Class="WellformationDesktopApplication.ConfigWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WellformationDesktopApplication"
mc:Ignorable="d"
Title="ConfigWindow" Height="1" Width="1" Visibility="Hidden" WindowState="Minimized">
<Grid>
</Grid>
</Window>
with code as follows :-
Timer at = new();
public ConfigWindow()
{
BuildConfig();
InitializeComponent();
}
public void refreshconfig()
{
myObjects.Clear();
myObjects = NudgeManager.GetNudges();
NudgeHandler(myObjects);
}
public void BuildConfig()
{
myObjects.Clear();
myObjects = GetEvents(); // pulls a list of event names with intervals from the config file
EventHandler(myObjects); //Goes through the list of events and figures out when the next event is due based upon the interval in the configuration
ActionTimer();
}
private void ActionTimer()
{
at.Interval = 60000;
at.Elapsed += ChecktActions;
at.AutoReset = true;
at.Enabled = true;
}
private void ChecktActions(object sender, ElapsedEventArgs e)
{
//Go through the trigger times for all events and see if those time have passed, if they have raise a toast showing the event name.
//If an event is raised reset the trigger time for the event based upon the interval and reset that time.
}
and the visible window XAML is as follows :-
<Window x:Class="WellformationDesktopApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WellformationDesktopApplication"
mc:Ignorable="d"
ResizeMode="NoResize"
WindowStyle="None"
Title="MainWindow" Height="500" Width="800" Background="{x:Null}" Foreground="{x:Null}" AllowsTransparency="True">
<Grid x:Name="BG">
<TextBlock x:Name="Display" HorizontalAlignment="Left" Margin="546,13,0,0" Text="Show event name and appropriate information about the event here..." VerticalAlignment="Top" FontSize="22"/>
</Grid>
</Window>
With Code as follows :-
public MainWindow()
{
InitializeComponent();
setstyles();
this.MouseLeftButtonDown += delegate { DragMove(); };
}
We know that everything to do with the ConfigWindow works fine, we know it is closed upon suspend and a new one is opened on resume with new timings set and all the appropriate alerts working.
The issue is with MainWindow as after a suspend and resume it cannot be interacted with at all. The open button on the icon does nothing, if the window is opened is is completely frozen and cannot be interacted with in any way, and if a toast is clicked on the window does not open but the rest of the toast handling code works fine around it. This happens on Win8, Win10 and Win11.
Any help out there as I am completely at a loss for how this is happening?
Thanks
After much work and going through the code section by section commenting it out to see if it made a difference I have found the issue.
Buried deep inside the the code for the hidden window (4 calls to functions down the line) I found that the EventHandler() was also raising a listener for
SystemEvents.SessionSwitch += new SessionSwitchEventHandler(OnSessionSwitch);
With all the associated functions buried in a separate class that was not directly referenced from the window itself.
When this line was commented out everything worked fine, with it in and attached to the hidden window after Suspend/Resume of windows no UI changes would take place throughout the whole code (hence hidden window continued to working completely fine as it did not interact with the UI).
By lifting this code out into the APP space and handling it there rather than in a window the problem has gone away (though has revealed other issues that were not being handled upon Resume of Windows that I now have to fix).
So the answer is that for a WPF application listeners for SystemEvents of any type need to be housed int the APP code space and not within windows.
I have set the initial resize mode of the window to be "NoResize" as shown below.
<Widnow ... WindowStyle="None" ResizeMode="NoResize">
I want to change the resize mode to "CanResizeWithGrip" after this button is clicked.
<Button x:Name="btnResize" Content="Click Me!" Click="BtnResize_Click"/>
And this is my event.
private void BtnResize_Click(object sender, RoutedEventArgs e)
{
}
private void BtnResize_Click(object sender, RoutedEventArgs e)
{
this.ResizeMode = ResizeMode.CanResizeWithGrip;
}
Consider this code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Title = DateTime.Now.ToString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Hide();
new MainWindow().ShowDialog();
Show();
Debug.WriteLine(Title);
}
}
The XAML is trivial:
<Window x:Class="ShowHide.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<Button
Content="Test"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Click="Button_Click"/>
</Grid>
</Window>
If I go "up", it works as expected - this window gets hidden, the new one is created and is shown as a modal window. But when I close the currently visible window, all hidden windows "underneath" get shown at once and they're not modal anymore. Multiple lines appear in the output window.
However, if I comment out the Hide() call, the problem doesn't seem to arise, i.e. I get to close modal windows one by one in reverse.
To reproduce:
Run the code.
Press the "Test" button. The current window will hide and the new one will appear.
Press the "Test" button in the new window. Another window will be created again. You can repeat this step as many times as you want.
Close the window. Older windows will re-appear all at once and neither will be modal.
Is this by design? What would your workaround be?
This is by design, as you hide your Modal window and display it again using Show() rather than ShowDialog(), so you could modify your code as below:
bool isChild;
private void Button_Click(object sender, RoutedEventArgs e)
{
Hide();
new MainWindow() { isChild = true }.ShowDialog();
if (isChild)
{
ShowDialog();
}
else
{
Show();
}
}
The code works just as you write. You call a method Show(), but you should write ShowDialog(). Just change this code:
Hide();
new MainWindow().ShowDialog();
Show();
To:
Hide();
new MainWindow().ShowDialog();
ShowDialog();
I have a pretty simple problem but I can't get it to work. I want a MessageBox to appear each time I left click inside my form. I didn't know how to capture it on the whole form so I started of trying to capture my left click inside my WebBrowser1. However, nothing really happens when trying to trigger the event.
I declared the action as WebBrowser1_Mousedown.
private void WebBrowser1_Mousedown(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
MessageBox.Show("test");
}
}
What am I doing wrong?
My relevant XAML as follows:
<Window x:Class="IndianBrowser.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="488.806" Width="807.089" MouseDown="Window_MouseDown">
and now trying with the webbrowser:
<WebBrowser x:Name="WebBrowser1" HorizontalAlignment="Stretch" Height="auto" Margin="0,85,0,0" VerticalAlignment="Stretch" Width="auto" MouseDown="WebBrowser1_Mousedown"/>
If you look into MSDN documentation for WebBrowser class, you'll see that mouse events are not supported. What you can do instead is subscribe for HtmlDocument.MouseDown event.
Update
Here is small snippet that demonstrates how to do this in WPF, NOTE you will have to add reference to Microsoft.mshtml assembly:
public MainWindow()
{
InitializeComponent();
this.webBrowser1.Navigated += webBrowser1_Navigated;
this.webBrowser1.Source = new Uri("your url");
}
void webBrowser1_Navigated(object sender, NavigationEventArgs e)
{
HTMLDocumentClass document = this.webBrowser1.Document as HTMLDocumentClass;
document.HTMLDocumentEvents2_Event_onclick += document_HTMLDocumentEvents2_Event_onclick;
}
bool document_HTMLDocumentEvents2_Event_onclick(IHTMLEventObj pEvtObj)
{
// here you can check if the clicked element is your form
// if (pEvtObj.fromElement.id == "some id")
MessageBox.Show("test");
return true;
}
I am new to WPF. I have two windows, such as window1 and window2. I have one button in window1. If I click that button, the window2 has to open. What should I do for that?
Here is the code I tried:
window2.show();
Write your code in window1.
private void Button_Click(object sender, RoutedEventArgs e)
{
window2 win2 = new window2();
win2.Show();
}
When you have created a new WPF application you should have a .xaml file and a .cs file. These represent your main window. Create an additional .xaml file and .cs file to represent your sub window.
MainWindow.xaml
<Window x:Class="WpfApplication2.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>
<Button Content="Open Window" Click="ButtonClicked" Height="25" HorizontalAlignment="Left" Margin="379,264,0,0" Name="button1" VerticalAlignment="Top" Width="100" />
</Grid>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonClicked(object sender, RoutedEventArgs e)
{
SubWindow subWindow = new SubWindow();
subWindow.Show();
}
}
Then add whatever additional code you need to these classes:
SubWindow.xaml
SubWindow.xaml.cs
private void button1_Click(object sender, RoutedEventArgs e)
{
window2 win2 = new window2();
win2.Show();
}
Assuming the second window is defined as public partial class Window2 : Window, you can do it by:
Window2 win2 = new Window2();
win2.Show();
This helped me:
The Owner method basically ties the window to another window in case you want extra windows with the same ones.
LoadingScreen lc = new LoadingScreen();
lc.Owner = this;
lc.Show();
Consider this as well.
this.WindowState = WindowState.Normal;
this.Activate();
In WPF we have a couple of options by using the Show() and ShowDialog() methods.
Well, if you want to close the opened window when a new window gets open then you can use the Show() method:
Window1 win1 = new Window1();
win1.Show();
win1.Close();
ShowDialog() also opens a window, but in this case you can not close your previously opened window.
You will need to create an instance of a new window like so.
var window2 = new Window2();
Once you have the instance you can use the Show() or ShowDialog() method depending on what you want to do.
window2.Show();
or
var result = window2.ShowDialog();
ShowDialog() will return a Nullable<bool> if you need that.
You can create a button in window1 and double click on it. It will create a new click handler, where inside you can write something like this:
var window2 = new Window2();
window2.Show();
You can use this code:
private void OnClickNavigate(object sender, RoutedEventArgs e)
{
NavigatedWindow navigatesWindow = new NavigatedWindow();
navigatesWindow.ShowDialog();
}