I'm trying to use WPF NotifyIcon and Caliburn Micro together. My end goal is that I double click on the icon in my system tray to restore my window from a minimized state. Feel free to tell me if the way I'm trying to go about it is totally wrong.
I can see that there is a DoubleClickCommand on the TaskbarIcon (I don't see any DoubleClick event, which I would actually be happy to use, if it were available). Normally when working with commands while using Caliburn Micro, I would simply create, say, a Restore() method and a CanRestore property which would automatically be called by a button named Restore. How would I go about hooking things up so that Restore() is called upon a double click on the icon in the system tray?
EDIT - As per gleng's suggestion, I have now added an attached event, but double clicking the icon in the system tray still seems to do nothing. Code below.
xaml -
<tb:TaskbarIcon cal:Message.Attach="[Event DoubleClick] = [Action Restore]" />
VM -
public void Restore()
{
MessageBox.Show("moo"); // breakpoint on this line is never hit
}
public bool CanRestore
{
get { return true; }
}
Try the following:
<TaskbarIcon cal:Message.Attach="[Event TrayMouseDoubleClick] = [Action DoubleClickFunc]"/>
Notice that the event name is TrayMouseDoubleClick which I found by looking at the source code of the control, specifically the file named TaskBarIcon.Declarations.cs.
This file contains all dependency property definitions and routed events that are defined for the TaskBarIcon class.
How about you create an attached event?
<TaskbarIcon cal:Message.Attach="[Event DoubleClick] = [Action DoubleClickFunc]"/>
Then in your view model you'll have:
public void DoubleClickFunc()
{
// Your custom logic here
}
I've done this in the past and it works quite well.
Related
I am working in WPF with MVVM. I implemented WPF Extended Toolkit and I use ChildWindow, when I open the ChildWindow the property IsModal is enabled. But this property does not block navigating with Tab.
I need block the navigating with Tab when the ChildWindos is open.
I tried with Focusable property but does not serve.
I understand your issue is with the tab in the background when show the ChildWindow.
You should try modifying the property KeyboardNavigation.TabNavigation of de Window.
If you use MVVM pattern do something like this in the XAML:
<Window
KeyboardNavigation.TabNavigation="{Binding TabNavigationMode}"
>
In the ViewModel:
private KeyboardNavigationMode _tabNavigationMode;
public KeyboardNavigationMode TabNavigationMode
{
get { return _tabNavigationMode; }
set { _tabNavigationMode = value; RaisePropertyChanged("TabNavigationMode");
}
And create a Method like this that is invoked when you open and close the Child Window
public void IsTabNavigationEnable(bool isEnable)
{
if (isEnable) TabNavigationMode = KeyboardNavigationMode.Contained;
else TabNavigationMode = KeyboardNavigationMode.None;
}
I tried it and it works fine. The tab is disabled in the background but not in the ChildWindow.
This is a known issue and the extended tool kit team needs to work on it.In the mean time if you still like to implement this feature using the ChildWindow I would suggest to subscribe to PreviewKeyDown event and manually change the behavior of the tab and arrow keys when the childwindow goes modal.
The link for the issue is
https://wpftoolkit.codeplex.com/discussions/252462
I'm working on a WPF MVVM application. I'm showing some data in a datagrid. I've two buttons to Add and Edit the selected record. I've data in ViewModel and I've to show another window (view) and make sure that ViewModels should have no information about views.
Where should I create its view and viewmodel?
How to get the data back and update datagrid?
How can I achieve this in MVVM?
We have not yet decided to use any framework, so I've to create my own interface.
Note: This ended up being quite a long answer - please ask me if anything is unclear
The implementation of dialog windows is a contentious issue in MVVM designs, and different people use different approaches.
Like you, I've decided not to use any framework and implement most things by hand. When it comes to dialog windows, I choose to be pragmatic about my implementation of MVVM, by launching the Dialog Window from inside my ViewModel. Also, I allow each Dialog ViewModel to have a reference to the Window it is displayed in, so it can close it when appropriate (details below). This breaks some of the strict MVVM "rules", but it gets the job done.
The main downside of this is that it might break unit testing if you are testing something that goes through a dialog. However, you can go a long way without running into that problem and it has not bothered me yet.
I've built up a bit of a library of dialog ViewModels which I can easily extend. It's way too much code to post here, but I'll show you the highlights.
Base ViewModel for Dialogs
Each of my dialog windows has a ViewModel that inherits from DialogViewModelBase, which is similiar to my regular ViewModelBase in that it provides support for INotifyPropertyChanged etc. The interesting part is this public method, which I call from wherever to launch the Dialog:
/// <summary>
/// Creates window instance for this dialog viewmodel and displays it, getting the dialog result.
/// </summary>
public void ShowDialogWindow()
{
// This is a property of the DialogViewModelBase class - thus, each DialogViewModel holds a reference to its own DialogWindow:
this.DialogWindow = new Dialogs.Views.DialogWindow();
// Tell the DialogWindow to display this ViewModel:
this.DialogWindow.DataContext = this;
// Launch the Window, using a method of the Window baseclass, that only returns when the window is closed:
this.DialogWindow.ShowDialog();
}
Window launched in the above method will close when its Window.DialogResult property is set. This is why the DialogWindow is a property of the DialogViewModelBase class - when the subclassing dialog ViewModel wants to close the dialog window, it simply sets the result:
protected void CloseDialogWithResult(bool dialogWindowResult)
{
// Setting this property automatically closes the dialog window:
this.DialogWindow.DialogResult = dialogWindowResult;
}
Host Window for Dialog Views
The Dialogs.Views.DialogWindow class that the ShowDialogWindow method instantiates is defined in XAML and is a subclass of Window. It has two important features. The first is that it's primary content element is simply a ContentControl that binds to the current context. This allows me to define different Views for different subclasses of DialogViewModelBase, and the DialogWindow will host the corresponding View based on the type of the context:
<ContentControl Content="{Binding}" /> <!-- In reality this is inside a border etc but its simplified here for demonstration -->
The second important feature of the DialogWindow XAML is that it defines which dialog Views go with which dialog ViewModels. Here is a sample:
<Window.Resources>
<!-- DEFAULT ViewModel-View TEMPLATES -->
<DataTemplate DataType="{x:Type dialogs:YesNoMessageBoxDialogViewModel}">
<views:MessageBoxView />
</DataTemplate>
<DataTemplate DataType="{x:Type dialogs:ErrorDialogViewModel}">
<views:ErrorDialogView/>
</DataTemplate>
</Window.Resources>
What all this does, is that I can define dialogs as subclasses to DialogViewModelBase and implement a View for each, and then tell DialogWindow which View its ContentControl must show for which dialog ViewModel.
Launching a Dialog and getting results
Below is a sample from one of my application ViewModels, in which I launch a Dialog Window that allows the user to select an Asset Type for creation:
public void CreateNewAsset()
{
// Instantiate desired Dialog ViewModel:
Dialogs.NewAssetTypeSelectionDialogViewModel dialog = new Dialogs.NewAssetTypeSelectionDialogViewModel();
// Launch Dialog by calling method on Dialog base class:
dialog.ShowDialogWindow();
// Execution will halt here until the Dialog window closes...
// The user's selection is stored in a property on the dialog ViewModel, and can now be retrieved:
CalculatorBase.AssetTypeEnum newAssetType = dialog.AssetType;
switch (newAssetType)
{
// Do stuff based on user's selection...
}
}
PS: I should really write a blog entry about this - when I do, I will post the link here, as the blog entry will probably have more complete code samples.
It depends how you are handling the data. I will assume that changes made in the popup window can be accepted only when user clicks something like save in other case they should be discarded.
So firstly, I would suggest using MVC approach as controller is perfect for such tasks. You build viewmodels in it, assign them o views and show the views. VM's simply keeps data and commands, commands execute methods are kept in controller. In other words you have singleton class which manages your VM's and views.
You should check out Prism framework. It offers great things like view regios where you can inject different user controls on the runtime, commanding and MVC layering out of the box alongside IOC and DI patterns.
I'm working on my first project in WPF/XAML, and there's a lot I've not figured out.
My problem is simple - I need a window that has a bunch of fields at the top, with which the user will enter his selection criteria, a retrieve button, and a data grid. When the user clicks on the button, a query is run, and the results are used to populate the grid.
Now the simple and obvious and wrong way to implement this is to have a single module containing a single window, and have everything contained within it - entry fields, data grid, the works. That kind of mangling of responsibilities makes for an unmaintainable mess.
So what I have is a window that is responsible for little more than layout, that contains two user controls - a criteria control that contains the entry fields and the retrieve button, and a data display control that contains the data grid.
The question is how to get the two talking to each other.
Years back, I would have added a function pointer to the criteria control. The window would have set it to point to a function in the display control, and when the button was clicked, it would have called into the display control, passing the selection criteria.
More recently, I would have added an event to the criteria control. I would have had the window set a handler in the display control to listen to the event, and when the button was clicked, it would have raised the event.
Both of these mechanisms would work, in WPF. But neither is very XAMLish. It looks to me like WPF has provided the ICommand interface specifically to accommodate these kinds of connection issues, but I've not yet really figured out how they are intended to work. And none of the examples I've seen seem to fit my simple scenario.
Can anyone give me some advice on how to fit ICommand to this problem? Or direct me to a decent explanation online?
Thanks!
MVVM is the prevalent pattern used with WPF and Silverlight development. You should have a read up on it.
Essentially, you would have a view model that exposes a command to perform the search. That same view model would also expose properties for each of your criteria fields. The view(s) would then bind to the various properties on the view model:
<TextBox Text="{Binding NameCriteria}"/>
...
<Button Command="{Binding SearchCommand}".../>
...
<DataGrid ItemsSource="{Binding Results}"/>
Where your view model would look something like:
public class MyViewModel : ViewModel
{
private readonly ICommand searchCommand;
private string nameCriteria;
public MyViewModel()
{
this.searchCommand = new DelegateCommand(this.OnSearch, this.CanSearch);
}
public ICommand SearchCommand
{
get { return this.searchCommand; }
}
public string NameCriteria
{
get { return this.nameCriteria; }
set
{
if (this.nameCriteria != value)
{
this.nameCriteria = value;
this.OnPropertyChanged(() => this.NameCriteria);
}
}
}
private void OnSearch()
{
// search logic, do in background with BackgroundWorker or TPL, then set Results property when done (omitted for brevity)
}
private bool CanSearch()
{
// whatever pre-conditions to searching you want here
return !string.IsEmpty(this.NameCriteria);
}
}
I was wondering if there was a way to close a window when a property in the view model changes. In my situation I have a login window with an Ok button bound to a LoginCommand so that the function Login executes when Ok is clicked. If the login is successful, I want the window to close.
Now I know I could do this by adding an event handler on my button, which calls a function like this:
private void Button_Click(object sender, RoutedEventArgs e)
{
DatabaseCredentialsViewModel vm = (this.DataContext as DatabaseCredentialsViewModel);
vm.Login();
if (vm.LoginSuccessful)
{
this.Close();
}
}
But I was wondering if there was a way to close the window when LoginSuccessful property changes without having an event handler on my button (I like working only with command binding and not having event handlers on Click event).
Thank you
Here's a similar question, which filled my need.
Basically, you use an attached property for your window, which binds to a bool? property on your VM. When the VM property is set to something non-null, the attached property sets the Window's DialogResult, which will automatically close the window.
If you want you can try this different approach.
You can do this by associating the OK button with a command. Create an event such as LoginSuccess and when then add a window.Close() to the list of event callback. Then you have only to raise the LoginSuccess event to close the windows.
In my opinion, this respect the MVVM pattern defining an event that can be used for other trigger and not only for closing windows.
You could do this fairly easily by creating an attached property or Behavior (from Blend SDK) that hooked into your Window.
I posted a sample behavior to the Expression Code Gallery which does something similar (though definitely different) - it prevents a window from being closed via a property on the VM. You could very easily adapt the code (included in the download) to just close the window on a property change.
within my current project file I have a user control that has a storyboard animation applied to the control. When a button is clicked in the page the storyboard starts and basically visually presents the control to the user. The storyboard resides in the current page as a resource
<navigation:Page.Resources>
<Storyboard x:Name="PreferncesOpen">....</Storyboard x:Name="PreferncesOpen">
</navigation:Page.Resources>
Within the page I have button that I have a click event on that starts the storyboard
private void btnOpenPreferences_Click(object sender, RoutedEventArgs e)
{
preferencesPanel.Visibility = System.Windows.Visibility.Visible;
PreferncesOpen.Begin();
}
Within the userControl (preferencesPanel) I have a button that when clicked needs to close/collapse the user control. I plan to do this using Visibility.collapsed. I assume that I need to use routed commands since the button is within the user control but the actions need to be called within the page that contains the control? I'm still new to routed commands and I assume this is the correct approach. I'm just unsure how to click on a button within the user control and have it modify or execute commands that would impact how the page (in which this control resides) may change or for that part affect other elements within the page? For example when the button is clicked within the user control I would like the visibility of the user control to be set to collapsed. I also would like to have the width of one of the grid columns within the main page re-size. I have done this in the past using the code behind for the page but I am trying to separate some of this and I thought routed commands would be the way to go?
I'd greatly appreciate any tips.
Thank you in advance
The title is a bit misleading, you're asking about commands rather then routed events if I understand you correctly.
Here's an example of using a DelegateCommand<T> from the Prism library; It happens to be my personal preference.
Markup :
<Button x:Name="MyButton" Content="Btn" Command="{Binding DoSomethingCommand}"/>
Code-behind* or ViewModel :
(* if you're not using MVVM make sure to add MyButton.DataContext = this; so you're sure that the button can databind to your code behind effectively)
public DelegateCommand<object> DoSomethingCommand
{
get
{
if(mDoSomethingCommand == null)
mDoSomethingCommand = new DelegateCommand(DoSomething, canDoSomething);
return mDoSomethingCommand;
}
private DelegateCommand<object> mDoSomethingCommand;
// here's where the command is actually executed
void DoSomething(object o)
{}
// here's where the check is made whether the command can actually be executed
// insert your own condition here
bool canDoSomething(object o)
{ return true; }
// here's how you can force the command to check whether it can be executed
// typically a reaction for a PropertyChanged event or whatever you like
DoSomethingCommand.RaiseCanExecuteChanged();
The argument that's passed to the above function is the CommandParameter dependency property (in Prism it's an attached property as well as the Command property if memory serves me right).
When it's set, you can pass a value of your choosing to the command that you wish to execute.
Hope that helps.