A super-simple MVVM-Light WP7 sample? - c#

I am looking for a sample that demonstrates in the lightest way possible the following:
A Model that invokes a SOAP based web service; regularly polling to get the latest value (assume the SOAP service returns a boolean). The model should also support invoking a SOAP method that changes the boolean on the server.
A ViewModel that enables the underlying boolean to be bound to controls in the View (e.g. to a checkbox).
A View with the above checkbox control bound to the underlying boolean. Depending on the poll interval the checkbox will update as the server's state changes. If the checkbox is clicked the event will be dispatched to the model causing the server to be updated.
Optimally this sample will work on Windows Phone 7, but in a pinch I'd be happy with something that supported SL3 (no use of SL4 command routing allowed).
I am struggling with trying to understand how to make MVVM-Light work for me and I suspect that an expert could code a sample up like this very quickly... I also suspect this is a fairly common pattern for a lot of apps.

Mick N's pointer helped, but what really got me over the hump was this post by Jeremy Likness:
http://csharperimage.jeremylikness.com/2010/04/model-view-viewmodel-mvvm-explained.html
Here's the sample for the benefit of others (assuming I'm not doing anything really stupid):
First, I started using the Mvvm-Light Windows Phone 7 project.
I added a checkbox to my MainPage.xaml:
<CheckBox Content="Switch 1"
IsChecked="{Binding Switch1.PowerState, Mode=TwoWay}"
Height="72" HorizontalAlignment="Left" Margin="24,233,0,0"
Name="checkBox1" VerticalAlignment="Top" Width="428" />
Notice the IsChecked is bound to Switch1.PowerState using the TwoWay mode so that the property flows both ways.
A key learning for me is how to enable communication from my timer callback (TimerCB) which will be running on a new thread to the Silverlight UI thread. I used the Mvvm-Light DispatcherHelper.CheckBeginInvokeOnUI helper which waits on the UI thread.
I then had to decide whether to implement INotifyPropertyChanged myself in my model, or use Mvvm-Light's ViewModelBase implementation. I actually tried it both ways and had it working but decided I liked using ViewModelBase better because it supports "broadcast" and I think in my actual project that will be handy because I will have multiple ViewModels. It seems a bit uncouth to be basing a "Model" on ViewModelBase class, but I don't think there's any harm in doing so. (???).
My model .cs is below.
public class OnOffSwitchClass : ViewModelBase // ignore that it's derived from ViewModelBase!
{
private const Int32 TIMER_INTERVAL = 5000; // 5 seconds
private Timer _timer;
// Upon creation create a timer that changes the value every 5 seconds
public OnOffSwitchClass()
{
_timer = new System.Threading.Timer(TimerCB, this, TIMER_INTERVAL, TIMER_INTERVAL);
}
private static void TimerCB(object state)
{
// Alternate between on and off
((OnOffSwitchClass)state).PowerState = !((OnOffSwitchClass)state).PowerState;
}
public const string PowerStatePropertyName = "PowerState";
private bool _myProperty = false;
public bool PowerState
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
// Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
RaisePropertyChanged(PowerStatePropertyName, oldValue, value, true));
}
}
}
The MainViewModel.cs was modified to include the following
private OnOffSwitchClass _Switch1 = new OnOffSwitchClass();
public OnOffSwitchClass Switch1
{
get
{
return _Switch1;
}
}
And I added a call to DispatcherHelper.Initialize(); in my App() constructor.
Does this look right?

Related

Bind to property from another project in same solution

I'm pretty new to WPF, and now I stumbled on something for which I could not find the answer anywhere on the internet. I have the following problem:
Within the same solution, I have 2 projects. One is an application that represents a production process, called MaintenancePlanner. The other is a GUI called MaintenancePlannerGUI.
What I want to achieve is the following: upon pressing a button, the simulation of my production process starts (which takes place in MaintenancePlanner). Then, in the MaintenancePlannerGUI, I have for example a progressbar. The value of the progressbar should change according to the value of the property of an object within the MaintenancePlanner simulation.
Therefore, I need to bind this somehow. However, I don't understand how to do this. I make use of the MVVM structure. So my structure looks like follows:
MaintenancePlanner
AssemblyFab.cs
AssemblyLine.cs
ShellModel.cs (something like Program.cs, but specifically to be used for MaintenancePlannerGUI only)
MaintenancePlannerGUI
Views
ShellViewModel.cs
ViewModels
ShellView.xaml
Now, AssemblyLine for example contains a property Speed. Note that multiple instances of AssemblyLine are attached to AssemblyFab, in the form of a List<AssemblyLine> AssemblyLines.
In ShellView.xaml I have a progressbar:
<ProgressBar Width="10" Height="45" Margin="0,5,10,0" Orientation="Vertical" Minimum="0" Maximum="50" Value="{Binding ???}"/>
In ShellViewModel.cs I create an instance of the MaintenancePlanner simulation AssemblyFabSim by creating an instance of ShellModel.cs from MaintenancePlanner where the whole AssemblyFab and its constituents are created, like this:
AssemblyFabSim = new ShellModel();
Now, I tried something very crude like:
Value="{Binding AssemblyFabSim.AssemblyFab.AssemblyLines[0].Speed}
But that obviously didn't work. Another idea that came to my mind is to make use of the NotifyPropertyChanged Methods.
So in that case, I could create a property in ShellViewModel.cs named for example test and bind that to my progressbar. Then I could update test by getting a notification if the property changed in the ShellModel.cs. But then I also need to monitor the changes in AssemblyFab and AssemblyLine from within ShellModel.cs, so to propagate the change from AssemblyLine to AssemblyFab to ShellModel to ShellViewModel to the View. And I am a little bit confused about this approach.
private void ShellModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Speed")
{
test = AssemblyFabSim.AssemblyFab.AssemblyLines[0].MouldCleanInterval;
}
}
I was wondering whether this is indeed the way to go, and if so, how to do this exactly? Or are there perhaps other simpler ways? Thanks in advance!
Edit 1
My ShellViewModel.cs now contains the following, as ShellViewModel inherits the INotifyPropertyChanged class like this ShellViewModel : INotifyPropertyChanged
public ShellModel AssemblyFabSim { get; set; }
AssemblyFabSim.PropertyChanged += ShellModel_PropertyChanged;
private void ShellModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "TestSpeed")
{
test = AssemblyFabSim.AssemblyFab.AssemblyLines[0].Speed;
}
}
private double _test;
public double test
{
get { return _test; }
set
{
_test = value;
NotifyOfPropertyChange();
}
}
And I now bind my progressbar value like Value="{Binding test}. Then ShellModel.cs also will inherit INotifyPropertyChanged and I add:
public void UpdateSpeed()
{
try
{
TestSpeed = AssemblyFab.AssemblyLines[0].Speed;
}
catch (Exception e)
{
throw new Exception(e.Message);
}
NotifyOfPropertyChange(nameof(TestSpeed));
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyOfPropertyChange([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
And the UpdateSpeed() method is called from within the Assemblyline.
New problem: The value of the processbar gets updated, but only after the simulation is finished I see the result. That is, the GUI just freezes until the simulation stops and it then shows the last value of Speed.
If your shellViewModel has a property like
public ShellModel AssemblyFabSim {get;}
you should be able to bind to it, and if all the other properties in the path is correct they should also work. But as far as I know, bindings does not support indexers, so I do not think AssemblyLines[0] will work.
Wpf does not care about what projects classes are defined in, only that it has a object to bind to, and the properties are correctly named. Usually everything should also implement INotifyPropertyChanged to work well.
But note that deeply nested paths is probably not a good idea, you should try to separate the UI and business logic, so you should try to avoid binding to anything other than viewModel classes designed for it.
Notably, if you have a progress bar you should bind to a Progress<T> object that is handed to the method that needs to report progress. You should avoid using a progress-property on the object performing the work, after all, what would happen if the method was called concurrently from multiple threads?
You need to ensure that you are calling the UpdateSpeed() on a background thread since the UI thread cannot both update the progress bar and execute your code simultaneously.

Best way of passing values between UI and Code modules in Xamarin

I am in the process of creating a cross platform app in Xamarin for Android and IOS.
The app needs to return the location of the device (Longitutue, Latitude, first line of address)
It also needs to read specific data from Mifare Ultralight Fobs.
When presented with an 'Admin Fob' the app will switch to Write Mode allowing the user to program Fobs for other users.
I have solved the basic issues in that I can get the address details and read / write data to a Fob.
As Xamarin is constantly evolving I was wanting to know what the best approach is to passing information back and forth between the UI and the underling code modules.
There seems to be
1) use static variables
2) Dependency Injection
3) Messaging Centre
I am also very new to Xamarin.
Static Variables are not a good choice for UI values unless you know what you're doing.
The simplest approach is like #MindSwipe said the MVVM pattern. Create a simple ViewModel, set it as BindingContext and use Binding in XAML. Its mostly the same as WPF, so you can use many guides for WPF which works also for Xamarin.
Here is a simple example:
public class MyViewPage : ContentPage
{
MyVieModel ViewModel = null;
public MyViewPage(){
this.BindingContext = ViewModel = new MyViewModel();
}
}
The ViewModel:
public class MyViewModel : INotifyPropertyChanged
{
private int _Counter = 0;
public int Counter
{
get { return _Counter; }
set
{
_Counter = value;
OnPropertyChanged(nameof(Counter));
}
}
}
and on XAML just simple Binding:
<Label Text="{Binding Counter}" />
Binding works with Two-Way Binding by default, so when you set the Counter, the UI is updated imidiately.

UI automation testing of WPF controls seems to ignore bindings

I'm currently trying to figure out how to automate UI testing for my WPF application and I have troubles getting it to work.
The XAML of MyControl (which extends UserControl) contains the following CheckBox:
<CheckBox Name="IsFooCheckBox"
IsChecked="{Binding Path=IsFoo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
The binding points to a custom data context that implements INotifyPropertyChanged and that contains the following property:
private bool _isFoo;
public bool IsFoo
{
get { return _isFoo; }
set
{
_isFoo = value;
OnPropertyChanged("IsFoo");
}
}
The binding is working in production (in the debugger is can see that _isFoo is updated whenever I toggle the checkbox).
I'd like to have a test now that toggles the checkbox and checks that the data context is updated (or to check logic that is implemented in the code-behind). The WPF UI Automation framework seems to be exactly what I am looking for, so I wrote the following NUnit test:
var myContext = ...
var sut = new MyControl
{
DataContext = myContext
};
var peer = new CheckBoxAutomationPeer(sut.IsFooCheckBox);
var pattern = peer.GetPattern(PatternInterface.Toggle) as IToggleProvider;
pattern.Toggle();
Assert.That(sut.IsProvidingProfileCheckBox.IsChecked.Value); // works
Assert.That(myContext.IsFoo); // fails
While the first Assert passes, the second one fails. I do not understand why this happens... it seems that the binding in the XAML file is ignored or that the update is not triggered. Does anybody have a suggestion how to fix my test? Is this even possible?
Issue originates here
public bool IsFoo
{
get { return _IsFoo; }
set
{
_isFoo = value;
OnPropertyChanged("IsFoo");
}
}
Once you have invoked
pattern.Toggle();
you implicitly invoke setter of IsFoo which raises PropertyChanged event and in turn forces to refresh UI elements which have binding associated with IsFoo - to cut a long story short, getter is invoked and instead of _isFoo it returns _IsFoo. You mistook variable.
Try to avoid calling OnPropertyChanged method with explicit property name. Instead of this use CallerMemberName attribute which retrieves property name.
public void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
Then you only need below invocation.
OnPropertyChanged();
I had similar problem. I was populating textbox with following code:
ValuePattern valuePattern = promptBox.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
valuePattern.SetValue(value);
And depending on the value in text box, another button state was supposed to change from Disabled to Enabled.
I've noticed that after automation code above executed, clicking on the window by hand triggered binding to evaluate.
So I just added
System.Windows.Forms.SendKeys.SendWait("{TAB}");
after SetValue and it started to work just fine.
It took me some time to figure this out, but in the end, it is kind of obvious and described in many places all over the internet. I guess everything is easy as soon as you know what to look for...
The problem of coded UI tests is that the bindings are not resolved automatically. The resolving has to be initiated by calling Window.ShowWindow.
I extended my test and added the following snippet:
Window window = new Window
{
Content = sut // the control to test
};
window.Show();
Adding this call instantaneously fixed the strange test behavior that I described in my post.
The direct follow-up problem is that this call requires an active UI thread. Because of this, it might be tricky to get the test to run on a build server in a continuous integration environment. However, this depends on the environment (esp. the build server) and is a different question.

How to process events fast during a busy process, is there an Update command?

During a lengthy (about 1 minute) process I am trying to log some progress by writing time-stamped messages to a text control. But all messages appear at once. Apparently, all PropertyChanged events are queued until my busy process is done, and received by the text control all at once. How can I kind of 'flush' the events in the middle of my busy process? I searched but could not find a Flush/Update/Dispatch call to immediately process queued events.
A multi threaded solution is in question 1194620, but I would first like to avoid multithreading if possible. In older environments (C++, .Net Winforms/ASP) there were always system calls like Update to interrupt a busy process to handle pending events.
Edit: Please don't tell me that that a lengthy process should be in another thread. I agree. But this is inherited code, and before I would even think about converting to multithreaded, I first need to log certain events to understand what it does. Besides, this app has many other problems that need to be fixed first. Also, after fixing problems, the lengthy process might not be lenghty anymore.
The method of writing strings from anywhere in de code I found in question 18888937 and works fine.
This is the code-behind.
Edit: I added the call to the solution in the Accepted Answer.
public partial class App : Application, INotifyPropertyChanged
{
/// <summary>
/// Property for the log message for the TextBlock control
/// </summary>
public string StartupMessage
{
get { return _StartupMessage; }
set
{
if (_StartupMessage.Length == 0)
{
_StartupMessage = string.Format("{0:HH-mm-ss} {1}",
DateTime.Now, value);
}
else
{
_StartupMessage = string.Format("{0}{1}{2:HH-mm-ss} {3}",
_StartupMessage, Environment.NewLine, DateTime.Now, value);
}
OnPropertyChanged("StartupMessage");
}
}
private string _StartupMessage = "";
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
DoEvents();//see the accepted answer below
}
}
this is the text control:
<TextBlock x:Name="textblock_StartupMessages"
Margin="10" TextWrapping="Wrap"
Text="{Binding Path=StartupMessage, Source={x:Static Application.Current}}">
</TextBlock>
and here is how I place messages from another place in the code:
public class AllRoutesViewModel : ViewModelBase
{
public AllRoutesViewModel()
{
(System.Windows.Application.Current as App).StartupMessage =
"start of AllRoutesViewModel()";
avoid multithreading if possible. In older environments (C++, .Net
Winforms/ASP) there were always system calls like Update to interrupt
a busy process to handle pending events.
This is attempting a design pattern on a system which was designed not to behave like the systems you mentioned.
Long running operations should not be done on the GUI thread in WPF.
Notify property change only works when the GUI thread is not blocked because it is inherently a GUI process. The code you have is blocking the GUI thread. If you properly run the task in a background worker, or an async task and properly update your property, the notify will make the GUI behave visually as you actually want and expect.
But by the design you present, to graphically do this is impossible. The best answer is to learn the WPF design pattern and follow it, instead of forcing a different technologies design pattern.
You might consider using Dispatcher.PushFrame.
More information is available about the class here.
Also, here is the relevant code sample from MDSN (slightly modified):
using System.Windows.Threading; //DispatcherFrame, needs ref to WindowsBase
//[SecurityPermissionAttribute(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)]
public void DoEvents()
{
DispatcherFrame frame = new DispatcherFrame();
Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Background,
new DispatcherOperationCallback(ExitFrame), frame);
Dispatcher.PushFrame(frame);
}
public object ExitFrame(object f)
{
((DispatcherFrame)f).Continue = false;
return null;
}
While this solution might give you want you want in this case, I have to agree with what others have said about design patterns. Please consider something like MVVM in the future.

mvvmcross IOS: How to callback from a ViewModel to a View

I have a MvxViewController and in the ViewDidLoad i bind the button click to the viewmodel. When the button is clicked I open another view in which I will need to return a string back to my first view
public override void ViewDidLoad ()
{
var set = this.CreateBindingSet<MyView1, MyView1ViewModel>();
set.Bind(myButton).To(vm => vm.MyButtonCommand);
set.Apply();
}
public ICommand MyButtonCommand
{
get
{
_myButtonCommand = _myButtonCommand ?? new MvxCommand(MyButtonCommandClick);
return _myButtonCommand;
}
}
private void MyButtonCommandClick()
{
ShowViewModel<ViewModelNumber2>();
}
After some logic is ran in my second view I want to return the string
private void SomeMethodInViewModelNumber2()
{
//Raise event that will get pickup up in MyView
//Or somehow get "SomeString"
if (OnMyResult != null)
OnMyResult ("SomeString");
}
The problem is that I don't want to send the string back using the messenger. I have my reasons but basically because ViewModelNumber2 can be opened from many different places and works slightly different and managing the different messages that would need to be sent back and where to subscribe to these messages would be a mess
Is there any way that I can do something like the below?
public override void ViewDidLoad ()
{
var set = this.CreateBindingSet<MyView1, MyView1ViewModel>();
set.Bind(myButton).To(vm => vm.MyButtonCommand).OnMyResult((myString) => {Process(myString)});
set.Apply();
}
Or perhaps when I create ViewModelNumber2 I should pass a callBack into the constructor and use that to send the string back from ViewModelNumber2 to MyView1ViewModel
ShowViewModel<ViewModelNumber2>(OnMyResult);
What is the best way to do this?
In short: I don't know what "the best way to do this" is.
The area of ChildViewModel-ParentViewModel messages is complicated - especially because on platforms like Android using Activities and WindowsPhone using Pages you have no guarantee that the ParentViewModel will be in memory when the Child is shown. (Note: this isn't a problem on iOS as its "app suspension" model is simpler)
When I do need one ViewModel returning data to another, then:
Often I try to implement the data collection views as "popup dialogs" rather than as "whole pages" - this makes the parent-child ViewModel relationship more correct - and ensures the parent ViewModel will be in memory when the child closes.
Often I recommend people use a Messenger-based technique like Greg describes in: http://www.gregshackles.com/2012/11/returning-results-from-view-models-in-mvvmcross/
often I've done this messaging via background services rather than via ViewModel-ViewModel messaging (a bit like the way screens are updated in https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/tree/master/N-17-CollectABull-Part6)
Another solution I've used is to:
implement a IDropBoxService singleton - with an API like void Deposit(key, value) and bool TryCollect(key, out value)
allow the closing "child" ViewModels to leave "values" when they close
implement IVisible functionality in my "parent" ViewModel - like in https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-42-Lifecycles/Lifecycle.Core/ViewModels/FirstViewModel.cs#L10
use the IVisible method to check for messages
To implement anything perfectly, you really should add serialisation code to make sure this all works during "tombstoning" on all platforms... but often this is overkill - for a simple data collection dialog users often don't need "perfect" tombstoning support.

Categories

Resources