WPF Navigation and Rotating Backgrounds - c#

I'm working on an application, and I'm using the MVVM approach.
Basically, there are currently two Pages, and 1 MainWindow.
I switch between the pages using a Frame inside MainWindow.
In the main window, there are 2 buttons which are basically global and should show in all pages; x (exit) and settings.
This is basically my 'shell', as I decided to not use a window border.
The problem is I'd like each page to have a different background and this is where it gets complicated:
- Settings page: Grey background.
- Main Page: Rotating background color that changes according to a property.
The thing is the background is being set in the main window, because it should apply to the global area as well (the top, where the exit and settings buttons are).
I first set the background (in MainWindow) as bound to a property the represents the current page (the value is then being translated into a color hex code with the help of a converter).
All in all, this results in a case where the background changes when a page is changed, but not when the property inside MainPage changes. I can clearly understand why, but I have no idea how to solve it.
The possible solutions I came up with so far:
Somehow causing the binding in MainWindow to update/refresh when the property is changed in MainPage.
Changing the background manually from inside each of the pages. (Although doesn't it negate the idea of mvvm?)
Move the background into each of the pages and set it from there, while making the global buttons on top of the page (which could be a bad thing in case controls end up overlapping).
If so, what would be the best solution to this problem?

If you haven't already, I'd suggest you install some package via NuGet to make MVVM style development more enjoyable. I personally prefer MVVMLight which is... well, light, but it also packs lot's of helpful features.
To communicate between ViewModels, you have (at least) two possible approaches.
1) ViewModelLocator (not recommended)
ViewModelLocator is central place holding references to all of your viewmodels. You could add a property that is then used by all of the viewmodels to get/set the background.
....
x:Name="Main"
DataContext="{Binding Source={StaticResource Locator}, Path=MainVM}">
....
<Grid Background="{Binding Background, Converter={StaticResource StringBrushConverter}}">
...
2) Messenger (recommended)
When ever property changes in your viewmodel(s) or method is executed, you could send a message that your MainViewModel is registered to listen to. Sending a message would be as easy as...
Messenger.Default.Send(new UpdateBackgroundMessage(new SolidColorBrush(Colors.Blue)));
And you'd register for this message in your MainViewModel's constructor:
Messenger.Default.Register<UpdateBackgroundMessage>(this, message =>
{
Background = message.Brush;
});
Actual message class would be:
public class UpdateBackgroundMessage : MessageBase
{
public UpdateBackgroundMessage(Brush brush)
{
Brush = brush;
}
public Brush Brush { get; set; }
}
I know I'm simplifying things here but I hope you got the idea. Both approaches are valid even if you decide not to use MVVMLight.
Edit:
Here's Git repo with example https://github.com/mikkoviitala/cross-viewmodel-communication

I think you should use Application Properties for storing background. There are various benefit of this :
1) Globally available
2) Easy to remember or store user preference
3) Automatically maintain separate profile for each user as it store values in AppData folder of user.
you can use Messenger to notify that background property has changed so that main window or shell could pull out new background value and update it.

Related

How to bind UWP Control's Methods to a Method or Command in MVVM

I am completely new to MVVM and I am creating an UWP app for keeping track of my software development, I am still learning.
So what I want to make is:
An app that contains single page ->
In MainPage.xaml I have something like this:
<!--MainPage Content-->
<Grid>
<!--For SearchBox-->
<AutoSuggestBox x:Name="SearchBox"/>
<!--For Adding Item-->
<AppBarButton x:Name="AddAppButton"/>
<!--Listview that contains main data-->
<ListView x:Name="AppsListView"/>
<!--This is DataTemplate of listview-->
<DataTemplate>
<Grid>
<!--Icon of App-->
<Image/>
<!--Name of App-->
<TextBlock/>
<!--For Editing Item-->
<AppBarButton/>
<!--For Deleting Item-->
<AppBarButton/>
</Grid>
</DataTemplate>
</Grid>
In Model I have something like this:
public class DevApp
{
public string name { get; set; } // For App Name
public string Iconsource { get; set; } // For App Icon
public ICommand EditCommand; // For Edit AppBarButton
public ICommand DeleteCommand; // For Delete AppBarButton
}
In ViewModel, something like :
public class ViewModel
{
// For ItemSource of ListView
public ObservableCollection<DevApp> DevApps = new ObservableCollection<DevApp>();
// For Add AppBarButton
public ICommand AddCommand;
}
Now this is me first time trying to create a neat and clean Mvvm app.
Now I have this question:
I know how to bind command to button or AppBarButton but how am I supposed to bind a Methods of a Xaml Control such as Listview's SelectionChanged() or AutoSuggestBox's TextChanged() Methods to ViewModel ?
How can I Load Data from save file ? As there is no InitializeComponent() in ViewModel like in CodeBehind to start from, where shall I pull LoadData() method which loads data to ListView ? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. )
Where shall I put Data class that can manage load save and edit data to savefile.
How shall I distribute responsibilities among classes ?
I have seen people using mvvm and they create files like:
services, helpers, contracts, behaviours, etc.
and I have seen same thing in Windows Community Toolkit Sample App
Is it required for Mvvm.
And what are services and helpers.
Shall I really use Mvvm for this ?
I tried using Mvvm in this just for curiosity but like
ITS BEEN 1 MONTH I AM MAKKING THIS APP! but it gets messed up again and again,
If I used Code Behind it would have been done in few days.
BY time now I realize that Mvvm is good at data bind in complex apps but
When it comes to simple things like a simple app with listview, I think code-behind
is better and it keeps things simple.
Please answer these questions I am really struggling in making this app.
I know how to bind command to button or AppBarButton but how am I supposed to bind a Methods of a Xaml Control such as Listview's SelectionChanged() or AutoSuggestBox's TextChanged() Methods to ViewModel
You could bind SelectionChanged with command by using Xaml Behavior InvokeCommandAction, or using x:bind markup extension to bind a method, for more please refer to this link.
How can I Load Data from save file ? As there is no InitializeComponent() in ViewModel like in CodeBehind to start from, where shall I pull LoadData() method which loads data to ListView ? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. )
Base on the first question, you could detect Page Loaded event and Invoke CommandAction where in the ViewModel. Then loading the file in the viewmodel LoadedCommand.
<i:Interaction.Behaviors>
<ic:EventTriggerBehavior EventName="Loaded">
<ic:InvokeCommandAction Command="{x:Bind ViewModel.LoadedCommand}" />
</ic:EventTriggerBehavior>
</i:Interaction.Behaviors>
Where shall I put Data class that can manage load save and edit data to savefile
The better place that savefile is current app's local folder, and it have full access permission, please refer to Work with files document.
How shall I distribute responsibilities among classes ?
I have seen people using mvvm and they create files like:
services, helpers, contracts, behaviours, etc.
and I have seen same thing in Windows Community Toolkit Sample App Is it required for Mvvm. And what are services and helpers.
For mvvm design, model view viewmodel are necessary. And it is not necessary to make services, helpers, contracts, behaviours, it should base on your design. For example if you want to make NavigateService, you need make static service class to manager current app's navigation. We suggest you make sample project with TempleStudio that contains some base service and behaviors.
Shall I really use Mvvm for this ?
I tried using Mvvm in this just for curiosity but like
ITS BEEN 1 MONTH I AM MAKKING THIS APP! but it gets messed up again and again,
If I used Code Behind it would have been done in few days. BY time now I realize that Mvvm is good at data bind in complex apps but
When it comes to simple things like a simple app with listview, I think code-behind
is better and it keeps things simple.
Your understanding is correct, But Decoupling(mvvm) your code has many benefits, including:
Enabling an iterative, exploratory coding style. Change that is isolated is less risky and easier to experiment with.
Simplifying unit testing. Code units that are isolated from one another can be tested individually and outside of production environments.
Supporting team collaboration. Decoupled code that adheres to well-designed interfaces can be developed by separate individuals or teams, and integrated later.
Improving maintainability. Fixing bugs in decoupled code is less likely to cause regressions in other code.
In contrast with MVVM, an app with a more conventional "code-behind" structure typically uses data binding for display-only data, and responds to user input by directly handling events exposed by controls. The event handlers are implemented in code-behind files (such as MainPage.xaml.cs), and are often tightly coupled to the controls, typically containing code that manipulates the UI directly. This makes it difficult or impossible to replace a control without having to update the event handling code. With this architecture, code-behind files often accumulate code that isn't directly related to the UI, such as database-access code, which ends up being duplicated and modified for use with other pages.

I'm trying to design a solution for a day/night color scheme and got stuck

I'm working on an app that has a "day" and "night" color palette that can change automatically. We're using Xamarin Forms and, for historical reasons, we're not using XAML but I speak XAML so I'm going to use it in this post.
I've approached it by creating a base type with a property for relevant colors like "dark text" or "header background", then implementing that type for both schemes. Then, I made a type that references one of those and raises a PropertyChanged even if it changes. So a day->night transition involves setting the property, then anything in the UI bound to a path like "ColorScheme.DarkText" changes. Nice.
Now I've got a ViewModel that wants to have different colors for some items in a list. I want those colors backed by this day/night change system, but I might have designed myself into a corner. I'll show you what I did and how I want to redesign, but I'm curious if there's a clever way to go about it without causing other problems.
Here's a VM for an item I'm binding to, let's all assume there's nothing unexpected in ViewModelBase:
public class ItemViewModel : ViewModelBase {
public string IconColorName { get...; set...; }
public string IconText { get...; set...; }
}
That ViewModel's contained in another boring ViewModel that makes up the rest of the page:
public class PageViewModel : ViewModelBase {
public ObservableColorScheme ColorScheme { get...; set...; }
public ObservableCollection<ItemViewModel> Items { get...; set...; }
}
OK, so what I'm going for is I'd like XAML for my item's template to look something like:
<StackLayout>
<StackLayout.Children>
<Label TextColor={Binding IconColor, Converter={StaticResource StringToColorConverter} />
...
</StackLayout.Children>
</StackLayout>
Right. OK. So now here's the problem. I can imagine building that IValueConverter and setting it up so it has the same concept of the right color scheme, then using the string value here to get the appropriate property. But I have a problem: there can only be one source for a binding, right? I need the color to change if EITHER the ColorScheme or IconColorName changes. My hunch is WPF could do that, but Xamarin can't?
The most obvious solution I've thought of is some kind of extra ViewModel, in XAML-unfriendly format for brevity:
public class ColorViewModel : ViewModelBase {
public Color Color { get...; set...; }
public ColorViewModel(string colorName, ObservableColorScheme colorScheme) {
colorScheme.PropertyChanged += (s, e) => {
if (e.PropertyName == colorName) {
Color = colorScheme.Get(colorName);
}
}
Color = colorScheme.Get(colorName);
}
}
I do NOT like this. These items are created and destroyed a lot, so that means that event handler needs to be unsubscribed. I don't want to have to think about that, and I can assume a maintenance programmer will forget. I've thought about retooling it to use a WeakReference for the event subscription but... that's getting really icky.
So I'm not really sure how to proceed, short of making the Page here detect color scheme changes and manually update its child views. That feels icky too. I've been thinking about it for a couple of days and nothing nice is presenting itself.
I'm open to "you're doing this terribly wrong, and there's some feature that would make this dramatically easier for you". I'm suspicious that feature is Styles, which I'm not using because 1) the aforementioned lack of using XAML and 2) our project is older than Style support in Xamarin Forms. Feel free to tell me to throw this design away, but please don't do so without showing me a quick example of the better way!
I don’t know xamarin nor C#, so maybe I’ll use the wrong terms, but this is how I would approach this problem:
I assume you have some kind of ViewModel hierarchy and you know the root of this hierarchy.
I would create a ColorScheme class with a static getter of the current color scheme and getters for each color. So you can create a subclass for day and night scheme. Also a void ApplyTo(ViewModelBase). I would create an ViewModelBase interface which has an void UpdateColorScheme() and List Items().
Ok, now, each ViewModel can use the UpdateColorScheme method to setup the view will be created.
Probably there is some kind of event to change the color scheme. This could be a button or a clock based trigger. This event sets the correct ColorScheme and simply calls ColorScheme.CurrentScheme().ApplyTo(rootViewModel). The ApplyTo method walks down the ViewModel hierarchy and calls UpdateColorScheme() for each ViewModel.
This isn’t very fancy but your don’t have to create dozens of objects for something which will change rarely (only twice a day). You only have one instance of ColorScheme and be instance for each Color and a separate method for color settings. But you don’t have to create and register events listeners all the time. The base class will enforce the maintenance programmer to use this concept so he can not forget to setup a event listener and you use the same code for setting up and updating the view.
And a little side note: opinion based questions are not allowed on Stack Overflow. There is a Core Review Page of StackOverflow, I think this question belongs there.

MahApps Metro DialogCoordinator: Display Dialog to span UserControl only (instead of entire window)?

I'm epxloring different ways to best show dialog windows in my application.
MahApp Metro's IDialogCoordinator seems quite useful, but I couldn't quite adjust it to my use case yet.
Say I'm creating a UserControl (view), whose ViewModel needs to be able to display dialogues.
These dialogues should, when displayed, overlay/span the UserControl only, NOT the entire Window in which the UserControl is hosted.
Is there any way to achieve this?
Default behavior always seems to span over the entire window, and I haven't found any way to change this yet.
So far, I've been using the Dialog coordinator in a very straightforward way, doing the following in my view:
<UserControl
xmlns:Dialog="clr-namespace:MahApps.Metro.Controls.Dialogs;assembly=MahApps.Metro"
Dialog:DialogParticipation.Register="{Binding}">
and set set the instance in my view's constructor by,
viewModel.Initialize(DialogCoordinator.Instance);
which I'd then call in the viewmodel via
IDialogCoordinator _DialogCoordinator; // set with viewModel.Initialize() called from the view
private async Task _SomeCmdExecute()
{
await _DialogCoordinator.ShowMessageAsync(this, "HEADER", "TEST");
}
Thanks!
Dialogs in MahApps.Metro are always at the window level (see the container PART_MetroActiveDialogContainer in the window's style.)
What you can do is changing the styling of dialogs, so they don't stretch horizontally accross the entire window. See the default template MetroDialogTemplate for reference.

Transitioning from View to View in WPF

I've been researching MVVM and WPF for a few weeks now, as I'm putting together a UI for an Application that another developer is doing the backend for. I don't have tons of GUI experience, so I'm just trying to figure it out as I go along.
I'm starting to understand the concept of keeping the backend code separate from the UI, but I can only find simple, one Window examples of MVVM online.
The application I'm designing is a Kiosk that moves step-by-step through a series of screens based on user input and scans. What is a good way to separate and design these transitions?
For example, I have a welcome screen that waits for the user to scan their ID. Once it gets their ID, it shows a new Window, or View, or whatever you want to call it, asking the user to confirm the scanned information and push the continue button.
Then it moves to a new screen where the user makes selections and so on until, and after a couple more "screens", the result is printed and it resets for the next user.
Are there any good implementation examples of this on the web?
EDIT: The application is full screen. My first instinct was to just design each screen as a separate window and Show() them one after the other, but this seems sloppy and I'm guessing it's not the best way.
Another thing I tried was to make each individual view a UserControl and load them in one main panel, one after the other based on the step. Once again, not sure this is the best method.
Add a Content Control in your MainView like below,
<ContentControl Content="{Binding CurrentView}"/>
Create DataTemplates for your different Views like below,
<DataTemplate x:Key="Viewer" DataType="{x:Type VM:TiffImageViewerViewModel}">//ViewModel Name
<view:TiffViewer/>//View Name
</DataTemplate>
MainViewModel
public object CurrentView { get; set; }
private TiffImageViewerViewModel _TiffImageViewerViewModel;
public TiffImageViewerViewModel TiffImageViewerViewModel
{
get
{
return _TiffImageViewerViewModel;
}
set
{
_TiffImageViewerViewModel = value;
}
}
Create the object and assign it to CurrentView.
This link gives more clarity

WPF and Prism View Overlay

I need some help with overlaying views using the prism framework.Its a little more complexed than that so let me explain.I could be over-thinking this as well :D
i have shell (wpf window) and i have 2 views(A & B - both usercontrols) in a module.
when the shell loads it loads view A. On view A i have a button to "popup" view B
for some user input. so naturally i would think to some sort of modal window/control, maybe even a popup. however the problem i face with the popup is that when i move the shell the popup remains fixed and it doesnt block events in view A. I've tried disabling view A to stop events being fired and i've also tried to use a to get the view B move with the shell. Only the canvas works but i now need a way to block it tho'. Is there anyway i can overlay a view on top of another view with prism? or how does everyone else create modal popups with prism & wpf? any advise or pointers would be greatly appreciated.
If you want to use embedded dialogs without an extra window, you can use Prism's RegionManager to achieve the outlined behavior. The trick is to put the PopUp region parallel to your main region in the visual tree:
<Grid>
<ContentControl cal:RegionManager.RegionName="MainRegion" IsEnabled={Binding IsNoPopUpActive} />
<ContentControl cal:RegionManager.RegionName="PopUpRegion"/>
</Grid>
Now use the RegionManager to put view "A" into the "MainRegion". Create a controller class similar to IPopUpDialogController. It should be responsible for putting your view "B" (or any other PopUpView in your application) into the "PopUpRegion" on demand. Addtionally, it should control a flag that signal the underlying "MainRegion" to be enabled or disabled. This way a user won't be able to play with the controls in your view "A" until the pop up is closed.
This can even be done in a modal fashion by using ComponentDispatcher.PushModal() before pushing a frame onto the Dispatcher. However, I would recommend avoid modal dialogs.
Update: As requested in a comment, the IsNoPopUpActive could be implemented in the backing view model. There you could link it to RegionManager's View collection for the popup region:
public bool IsNoPopUpActive
{
get { return _regionManager.Regions["PopUpRegion"].Views.Count() == 0; }
}
Remember to trigger a PropertyChanged event as soon as you modify the views collection (add/remove a popup).
Just for your information: nowadays I avoid disabling the controls in the background and instead insert a transparent panel. This avoids clicking on background controls. However, this does not handle keyboard input (tab-ing to controls). To fix the keyboard input you need to make sure that the keyboard focus is trapped in the popup (MSDN on WPF Focus concepts).
Adding the following focus attributes to the popup region should do the trick:
KeyboardNavigation.DirectionalNavigation="None"
KeyboardNavigation.ControlTabNavigation="None"
KeyboardNavigation.TabNavigation="Cycle"
KeyboardNavigation.TabIndex="-1"
If you are using WPF + MVVM with Prism you can take a look at this Message View overlay controller. The nice part about this approach is you can write unit tests on you view model using a mock overlay controller and have the mock controller return the result that the user would choose in the overlay.
You can find it here: http://presentationlayer.wordpress.com/2011/05/24/wpf-overlay-message-view-controller/
Hope this helps

Categories