I'm sure I'm overlooking something simple, but WPF is not something I generally work in, so I'm scratching my head a bit on this.
I am trying to show a "splash screen" for an application that is meant to run in the background. It's basically a process wrapper for Windows operating systems.
I have a WPF Window defined as such:
public partial class MainWindow : Window
{
private Timer _timer;
public MainWindow()
{
InitializeComponent();
ContentRendered += MainWindow_ContentRendered;
}
private void MainWindow_ContentRendered(object sender, EventArgs e)
{
_timer = new Timer(5000);
_timer.Elapsed += TimerOnElapsed;
_timer.Enabled = true;
_timer.Start();
}
private void TimerOnElapsed(object sender, ElapsedEventArgs e)
{
Dispatcher.Invoke(() =>
{
Hide();
Close();
});
}
~MainWindow()
{
_timer.Dispose();
}
}
public partial class MainWindow : System.Windows.Window, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/MySolution.WindowsWrapper;component/mainwindow.xaml", System.UriKind.Relative);
#line 1 "..\..\MainWindow.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
XAML looks like:
<Window x:Class="MySolution.WindowsWrapper.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:MySolution.WindowsWrapper"
mc:Ignorable="d"
Title="Splash" Height="100" Width="327" WindowStyle="None"
HorizontalAlignment="Center" VerticalAlignment="Center"
AllowsTransparency="True" WindowStartupLocation="CenterScreen" ShowInTaskbar="False" Topmost="True">
<Window.Background>
<ImageBrush ImageSource="my-logo-large.png"/>
</Window.Background>
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
</Grid>
</Window>
...in my Program.cs file, I have something like this:
[STAThread]
public static void Main(string[] args)
{
var splashScreen = new MainWindow();
splashScreen.Show();
SetupSystemTrayIcon();
var showConsole = args.Any(x => x.ToLowerInvariant().Contains("showconsole"));
StartService(showConsole);
WaitToDie();
}
The splash screen displays as expected... but the timer is never initialized, and never fires, so it never goes away.
From what I've read, the ContentRendered event is supposed to be fired when the window is shown... but that doesn't seem to happen. What am I doing incorrectly?
I suggest that you remove your custom Main method and move your code to the App.xaml.cs class's OnStartup method:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
SetupSystemTrayIcon();
var showConsole = args.Any(x => x.ToLowerInvariant().Contains("showconsole"));
StartService(showConsole);
}
}
Make sure that the StartupUri property is set to MainWindow.xaml in your App.xaml:
<Application x:Class="WpfApp2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApp2"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
Then you should get a dispatcher and a window that gets activated.
Related
**
I have 2 windows in app. mainwindow with 2 buttons and window1 with a
label. btn one opens window1 and btn 2 changes window1 label color.
**
public partial class MainWindow : Window
{
Window1 sWindow = new Window1();public MainWindow()
{InitializeComponent();
}
private void btnFirstWindow_Click(object sender, RoutedEventArgs e)
{
sWindow.Show();
}
private void btnChangeBackground_Click_1(object sender, RoutedEventArgs e)
{
sWindow.ChangeBackground();
}
}
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public void ChangeBackground()
{
if (lblShowUser.Background == Brushes.Green)
{
lblShowUser.Background = new LinearGradientBrush(Colors.Red, Colors.Red, 90);
}
else
{
lblShowUser.Background = Brushes.Green;
}
}
}
IF I remove this part
**
private void btnFirstWindow_Click(object sender, RoutedEventArgs e)
{
sWindow.Show();
}
** From mainwindow and add both windows at app xaml
Startup="App_Startup"
StartupUri="MainWindow.xaml">
public partial class App : Application
{
void App_Startup(object sender, StartupEventArgs e)
{
Window1 sWindow = new Window1();
sWindow.Show();
}
}
the method of label changing color when i press the other button doesnt work
am new to C# and wpf So when answering please also give explantion on what to be done to the code and why
expecting it to work even if changes are made regarding when the other page shows up but its not working
Create an object as a field from Window1 class, then you can access its objects.
Output (tested in Visual Studio 2017, .Net Framework 4.5.2):
Note: if this solution helps you, please mark as answer (don't forget to vote for me).
XAML (Mainwindow):
<Window x:Class="WpfApp.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:WpfApp"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="OpenButton" Click="OpenButton_Click" Content="Open" HorizontalAlignment="Left" VerticalAlignment="Center" Width="75" Margin="99,0,0,0"/>
<Button x:Name="ChangeColorButton" Click="ChangeColorButton_Click" Content="Changing color" HorizontalAlignment="Left" VerticalAlignment="Center" Width="99" Margin="331,0,0,0"/>
</Grid>
</Window>
XAML (Window1):
<Window x:Class="WpfApp.Window1"
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:WpfApp"
mc:Ignorable="d"
Title="Window1" Closing="Window_Closing" Height="300" Width="300">
<Grid>
<Label x:Name="Label" Content="Label" HorizontalAlignment="Center" VerticalAlignment="Center" Width="Auto"/>
</Grid>
</Window>
C# (MainWindow):
public partial class MainWindow : Window
{
Window1 W1 = new Window1();
public MainWindow()
{
InitializeComponent();
}
private void OpenButton_Click(object sender, RoutedEventArgs e)
{
W1.ShowDialog();
}
private void ChangeColorButton_Click(object sender, RoutedEventArgs e)
{
W1.Label.Background = new SolidColorBrush(Colors.Blue);
}
}
C# (Window1):
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
this.Visibility = Visibility.Hidden;
}
}
Thanks
I have a WPF application which shows a window as a DialogBox.
I want to close this DialogBox when I click anywhere on MainWindow in application.
Here I am adding one sample example to explain
MainWindow of application
<Window x:Class="WpfApplication1.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:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Open new Window" Click="Button_Click" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Window>
Code behind main Window
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Window1 temp_Window = new Window1();
temp_Window.ShowDialog();
}
}
}
Child window Which I try to close
<Window x:Class="WpfApplication1.Window1"
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:WpfApplication1"
mc:Ignorable="d"
Title="Window1" Height="300" Width="300" Deactivated="Window_Deactivated">
<Grid>
<TextBlock>New Window</TextBlock>
</Grid>
</Window>
Code behind This Child Window
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Deactivated(object sender, EventArgs e)
{
Close();
}
}
}
Thanks
you can do this with Deactivated event of your DialogBox window
something like this
XAML
<Window x:Class="WpfApplication1.Window1"
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:WpfApplication1"
mc:Ignorable="d"
Title="Window1" Height="200" Width="200" WindowStartupLocation="CenterScreen"
Deactivated="Window_Deactivated">
<Grid>
</Grid>
</Window>
Code
private void Window_Deactivated(object sender, EventArgs e)
{
this.Close();
}
If you call the DialogBox with ShowDialog the background window (which is the MainWindow) will be disabled until you close the DialogBox and it won't get any click, so there is no way for you to achieve what you want unless you call the DialogBox with Show method which won't lock the background window, then you can close the DialogBox whenever MainWindow GotFocus fires.
first declare your temp_window as a filed not as a local variable:
private Window1 temp_Window;
When you open the new window don't open it as a dialog otherwise, the events on the mainWindow will not be handled use Show() instead of ShowDialog() :
private void Button_Click(object sender, RoutedEventArgs e)
{
temp_Window = new Window1();
temp_Window.Show();
}
On your main window handle the mouseDown event:
MouseDown="MainWindow_OnMouseDown"
and close the tempWindow in the handler
private void MainWindow_OnMouseDown(object sender, MouseButtonEventArgs e)
{
tempWindow .Close();
}
You have to declare your second window as a global variable and call the .Hide() and .Show() commands like that:
MainWindow:
public partial class MainWindow : Form
{
private Dialog m_Dialog;
public MainWindow()
{
InitializeComponent();
m_Dialog = new Dialog();
this.Click += closeDialog;
}
private void closeDialog(object sender, EventArgs e)
{
m_Dialog.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
m_Dialog.Show();
}
}
It works just fine.
UPDATED:
Here is the same code for WPF. I did it in WinForms previously:
public partial class MainWindow : Window
{
private Dialog m_Dialog;
public MainWindow()
{
InitializeComponent();
m_Dialog = new Dialog();
this.MouseDoubleClick += onCloseDialog;
}
private void onCloseDialog(object sender, MouseButtonEventArgs e)
{
m_Dialog.Hide();
}
private void onButton(object sender, RoutedEventArgs e)
{
m_Dialog.Show();
}
}
You can use another event instead of MouseDoubleClick of course.
If you really want to close the window you would have to use the .Close() command and call the constructor of you window everytime.
I have 2 WPF windows. App.xaml.cs opnes the First Window and read some data while showing the status and then close it. Then App.xaml.cs opens the second window. When I debug code execute correctly but after closing the first window it close down the entire application. What am I doing wrong? Is it not possible in App.xaml.cs ?
Here is the code. (For this test I am using code behind instead MVVM) In this code I have put a button to close the first window.
App.xaml.cs:
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
TestWindow tw = new TestWindow();
bool? rslt = tw.ShowDialog();
if (rslt == true)
{
MainWindow mw = new MainWindow();
mw.Show(); //I am not sure why the Application close itself
}
}
}
TestWindow.xaml:
<Window x:Class="Shell.Startup.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300">
<Grid>
<Button x:Name="ButtonYes" Content="Yes" HorizontalAlignment="Left" Height="21" Margin="95,192,0,0" VerticalAlignment="Top" Width="66" RenderTransformOrigin="1.485,0.81" Click="ButtonYes_Click"/>
</Grid>
</Window>
TestWindow.xaml.cs:
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
}
private void ButtonYes_Click(object sender, RoutedEventArgs e)
{
DialogResult = true;
Close();
}
}
MainWindow.xaml:
<Window x:Class=" Shell.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>
</Window>
NOTE:
I also tried the Application_Startup as given in the answer here.
Change the Application Shutdown mode in App.xaml as below. Note the ShutdownMode="OnExplicitShutdown"
<Application x:Class="WpfApplication2.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
ShutdownMode="OnExplicitShutdown">
<Application.Resources>
</Application.Resources>
</Application>
Then your onStartup Method in App class shall be
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
TestWindow t = new TestWindow();
bool? res = t.ShowDialog();
if (res == true)
{
MainWindow mw = new MainWindow();
mw.Show();
}
else
this.Shutdown();
}
And finally we have to shutdown the app explicitly since we changed the shutdown mode to be so. Hence your MainWindow shall have the following code
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Closed += MainWindow_Closed;
}
void MainWindow_Closed(object sender, EventArgs e)
{
App.Current.Shutdown();
}
}
I have an app using MVVM Light which launches another app that I need to stop when the user closes the main app down.
I have created a Dispose() method that frees up resources, but what I don't understand is where I call Dispose().
For example, I noticed in the Application class definition there are is: public event ExitEventHandler Exit;
Can I add something to my App (see code below) that is triggered when the app is about to exit?
(I know there are many other question on this topic but they all seem to presume more c# knowledge)
App.xaml.cs...
namespace Module.Config
{
public partial class App : Application
{
static App()
{
DispatcherHelper.Initialize();
}
}
}
MainWindow.xaml...
<Window x:Class="Module.Config.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:ignore="http://www.ignore.com"
mc:Ignorable="d ignore"
Height="640" MinHeight="600"
Width="800" MinWidth="800"
Title="Config"
DataContext="{Binding Main, Source={StaticResource Locator}}"
Closing="Window_Closing"
>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="../Skins/MainSkin.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<Grid x:Name="LayoutRoot" Margin="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ContentControl Content="{Binding Side}" Grid.Column="0" />
<ContentControl Content="{Binding SelectedModule}" Grid.Column="1" />
</Grid>
</Window>
MainWindow.xaml.cs...
namespace Module.Config
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Closing += (s, e) => ViewModelLocator.Cleanup();
Messenger.Default.Register<DialogMessage>(
this,
msg =>
{
var result = MessageBox.Show(
msg.Content,
msg.Caption,
msg.Button
);
msg.ProcessCallback(result);
});
. . . . .
private void Window_Closing(object sender, CancelEventArgs e)
{
/*
I want to call Dispose() within AvigilonViewModel.cs
*/
}
}
}
AvigilonView.xaml...
<UserControl x:Class="Module.Config.Views.Modules.AvigilonView"
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:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:Module.Config"
xmlns:ignore="http://www.ignore.com"
mc:Ignorable="d ignore"
DataContext="{Binding Avigilon, Source={StaticResource Locator}}">
<Grid>
.....
AvigilonView.xaml.cs...
namespace Module.Config.Views.Modules
{
public partial class AvigilonView : UserControl
{
public AvigilonView()
{
InitializeComponent();
}
}
}
MainViewModel.cs......
namespace Module.Config.ViewModel
{
public class MainViewModel : ViewModelBase
{
private ViewModelBase m_selectedModule;
public ViewModelBase Side
{
get { return ServiceLocator.Current.GetInstance<SideViewModel>(); }
}
public ViewModelBase SelectedModule
{
get { return m_selectedModule; }
set
{
m_selectedModule = value;
RaisePropertyChanged("SelectedModule");
}
}
public MainViewModel()
{
Messenger.Default.Register<PropertyChangedMessage<object>>(this, (r) =>
{
if (r.PropertyName == "SelectedNode")
{
if (r.NewValue is RedSensor)
{
SelectedModule = ServiceLocator.Current.GetInstance<SensorViewModel>();
(SelectedModule as SensorViewModel).Sensor = r.NewValue as RedSensor;
}
else
{
SelectedModule = r.NewValue as ViewModelBase;
}
}
});
}
}
}
AvigilonViewModel.cs....
namespace Module.Config.ViewModel.Modules
{
public class AvigilonViewModel : ViewModelBase
{
....
public Dispose(){
/* code to get rid of unmanaged resources */
}
}
}
ViewModelLocator.cs...
namespace Module.Config.ViewModel
{
public class ViewModelLocator
{
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
//SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();
}
else
{
//SimpleIoc.Default.Register<IDataService, DataService>();
}
SimpleIoc.Default.Register<AppState>();
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<SideViewModel>();
SimpleIoc.Default.Register<AvigilonViewModel>();
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public SideViewModel Side
{
get
{
return ServiceLocator.Current.GetInstance<SideViewModel>();
}
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public AvigilonViewModel Avigilon
{
get
{
return ServiceLocator.Current.GetInstance<AvigilonViewModel>();
}
}
....
I've also noticed the line Closing += (s, e) => ViewModelLocator.Cleanup(); in the above. I have tried adding a method called `Cleanup() to AvigilonView.xaml.cs and AvigilonViewModel.cs but it doesnt seem to be getting called.
You can handle the Closing event of your MainWindow and do the processing there.
XAML:
<Window Closing="Window_Closing">
Code behind:
private void Window_Closing(object sender, CancelEventArgs e)
{
// Clean up your resources here.
}
I have a strange problem in my project. There are pages made from usercontrol and menu bar (also usercontrol).
Here is my usercontrol that contains few buttons
public partial class UpperBar : UserControl
{
public UpperBar()
{
InitializeComponent();
}
public event EventHandler EventbtClicked;
private void btConnect_Click(object sender, System.Windows.RoutedEventArgs e)
{
EventbtClicked(this, e);
}
}
I added this in my page as follows:
<local:UpperBar VerticalAlignment="Top" Grid.Row="0" Height="78" Grid.ColumnSpan="3" Margin="0,2,0,0"/>
And in my page tried to call event:
public PageStatus()
{
InitializeComponent();
Plc.ExecuteRefresh += new EventHandler(RefreshLeds);
UpperBar.EventbtCliced += new EventHandler(UpperBatButtonClick);
}
protected void UpperBarButtonClick(object sender, EventArgs e)
{
//do something
}
But I can't access my event using this UpperBar.EventbtCliced, why ?
You need to access the instance of your class UpperBar in PageStatus, not the class UpperBar itself!
The easiest way for you here:
Name your UpperBar in your XAML, example:
<local:UpperBar x:Name="_myBar" x:FieldModifier="private"/>
Then use this instance in your PageStatus.xaml.cs:
public partial class MainWindow : Window {
public MainWindow()
{
InitializeComponent();
_myBar.EventbtClicked += new EventHandler(UpperBarButtonClick);
}
protected void UpperBarButtonClick(object sender, EventArgs e)
{
//do something
}
}
Now if you are working seriously in WPF, you should really learn about Databinding and MVVM, catching event this way is not the best way to do it at all.
You should use Custom Command (RoutedUICommand) rather than bubbling event from user control.
here are some steps to follow in contrast to your approach:
1: create class myCustomCommand.
namespace WpfApplication1
{
public class myCustomCommand.
{
private static RoutedUICommand _luanchcommand;//mvvm
static myCustomCommand.()
{
System.Windows.MessageBox.Show("from contructor"); // static consructor is called when static memeber is first accessed(non intanciated object)
InputGestureCollection gesturecollection = new InputGestureCollection();
gesturecollection.Add(new KeyGesture(Key.L,ModifierKeys.Control));//ctrl+L
_luanchcommand =new RoutedUICommand("Launch","Launch",typeof(myCustomCommand.),gesturecollection);
}
public static RoutedUICommand Launch
{
get
{
return _luanchcommand;
}
}
}
}
In the xaml of UserControl:
<UserControl x:Class="WpfApplication1.UserControl1"
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:CustomCommands="clr-namespace:WpfApplication1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.CommandBindings>
<CommandBinding Command="CustomCommands:myCustomCommand.Launch" Executed="CommandBinding_Executed">
</CommandBinding>
</UserControl.CommandBindings>
<Grid >
<TextBox Name="mytxt" Height="30" Width="60" Margin="50,50,50,50" ></TextBox>
<Button Name="b" Height="30" Width="60" Margin="109,152,109,78" Command="CustomCommands:ZenabUICommand.Launch"></Button>
</Grid>
Now in User control code
Handle command_executed
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
mytxt.Text = "invoked on custom command";
}
}
}