Why not working: RelayCommand RaiseCanExecuteChanged - mvvm-light

When I call the PressCommand.RaiseCanExecuteChanged(); in the TimerOnElapsed method, nothing happened.
What could be the problem?
(GalaSoft.MvvmLight.WPF4 v4.0.30319 and GalaSoft.MvvmLight.Extras.WPF4 v4.0.30319)
Here is my test code:
using System.Timers;
using System.Windows;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
namespace CommandTest {
public class MainWindowVM : ViewModelBase {
public MainWindowVM() {
PressCommand = new RelayCommand(
() => MessageBox.Show("Pressed"),
() => _canExecute);
PressCommand.CanExecuteChanged += (sender, args) => System.Diagnostics.Debug.WriteLine(System.DateTime.Now.ToLongTimeString() + " CanExecuteChanged");
_timer = new Timer(1000);
_timer.Elapsed += TimerOnElapsed;
_timer.Enabled = true;
}
public RelayCommand PressCommand { get; private set; }
#region Private
private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) {
_canExecute = !_canExecute;
PressCommand.RaiseCanExecuteChanged();
System.Diagnostics.Debug.WriteLine("At {0} enabled: {1}", elapsedEventArgs.SignalTime.ToLongTimeString(), _canExecute);
}
private readonly Timer _timer;
private bool _canExecute;
#endregion
}
}
Thank you in advance

Explanation:
The TimerOnElapsed method runs on a Worker Thread but to invoke the PressCommand.RaiseCanExecuteChanged(); must be on the UI thread.
So this is the solution, the updated TimerOnElapsed method:
private void TimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs) {
_canExecute = !_canExecute;
Application.Current.Dispatcher.Invoke(PressCommand.RaiseCanExecuteChanged);
System.Diagnostics.Debug.WriteLine("At {0} enabled: {1}", elapsedEventArgs.SignalTime.ToLongTimeString(), _canExecute);
}

Related

xamarin.forms changing property of observablecollection does not update UI

I have an observrable collection in my class that contains checkboxes. I implemented a button to check all checkboxes at once. I tried just cycling through all elements and checking the box via binding:
void selectAll_clicked(System.Object sender, System.EventArgs e)
{
var x = sender as Button;
if (!allSelected)
{
allSelected = true;
x.Text = AppResources.DeselectAll;
foreach (var elem in contactList)
elem.isChecked = true;
}
else
{
allSelected = false;
x.Text = AppResources.SelectAll;
foreach (var elem in contactList)
elem.isChecked = false;
}
}
}
I am sure this effects the list, but the UI isnt updated at all.
How can I make sure the observablecollection "updates" visibly?
I also tried adding propertychanged handler:
private void SetList()
{
listview_contacts.ItemsSource = contactList;
contactList.CollectionChanged += items_CollectionChanged;
}
static void items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.OldItems != null)
{
foreach (INotifyPropertyChanged item in e.OldItems)
item.PropertyChanged -= item_PropertyChanged;
}
if (e.NewItems != null)
{
foreach (INotifyPropertyChanged item in e.NewItems)
item.PropertyChanged += item_PropertyChanged;
}
}
static void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
BUt this just says that the cast isnt valid...
Thank you
I was able to achieve that by altering my type like so:
public class ContactType : INotifyPropertyChanged
{
private string _name;
private bool _isChecked;
public string name
{
get => _name; set
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(name)));
}
}
public string phone { get; set; }
public string initials { get; set; }
public bool isChecked
{
get => _isChecked; set
{
_isChecked = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(isChecked)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}

Dependency service event

I am trying to call the event handler from droid side, however it doesn't get fired. everyone else works however this event doesn't get fired. I am not sure what am I doing wrong. I have my dependency service registered at MainActivity and set dependency in my service.
public partial class MainPage : ContentPage
{
DocumentResults results;
IScanService scanService;
public MainPage()
{
InitializeComponent();
results = new DocumentResults();
BindingContext = new MainPageViewModel();
System.Diagnostics.Debug.WriteLine("test cw");
Console.WriteLine("test cw");
scanService = DependencyService.Get<IScanService>();
scanService.ResultsParsedEvent += (s, ev) => { ResultsParsed(null, ev); };
}
void Button_Clicked(System.Object sender, System.EventArgs e)
{
scanService.ScanService();
if (!String.IsNullOrWhiteSpace(test))
{
scanService.Parsing(test);
}
}
private void ResultsParsed(DocumentResults results,EventArgs e)
{
Console.WriteLine("update ");
testLbl.Text = results.Name;
}
}
My interface
public interface IScanService
{
event EventHandler ResultsParsedEvent;
string ScanService();
void Parsing(string test);
void resultsParsed(DocumentResults results, EventArgs e);
}
Droid implementation
public class RegService : IScanService
{
public event EventHandler ResultsParsedEvent;
DocumentResults results;
public string Test;
public String ScanService()
{
Test = "scan";
return Test;
}
public void Parsing(string test)
{
Test = "parsing";
var results= new DocumentResults();
results.Name = Test;
Thread thread1 = new Thread(() => resultsParsed(results,null));
System.Threading.Thread.Sleep(10);
resultsParsed(results,null);
}
public void resultsParsed(DocumentResults results, EventArgs e)
{
ResultsParsedEvent?.Invoke(results, e);
}
}

Switch Toggling Event Using MVVM

I realized recently that a switch doesn't have a command. And i need to bind the toggling event to my view model. How do i go about it?
I tried to bind the command to Toggled event but the code is running into error
You can use EventToCommandBehavior to convert the event to command
create the EventToCommandBehavior class
using System;
using Xamarin.Forms;
namespace xxx
{
public class BehaviorBase<T> : Behavior<T> where T : BindableObject
{
public T AssociatedObject { get; private set; }
protected override void OnAttachedTo(T bindable)
{
base.OnAttachedTo(bindable);
AssociatedObject = bindable;
if (bindable.BindingContext != null)
{
BindingContext = bindable.BindingContext;
}
bindable.BindingContextChanged += OnBindingContextChanged;
}
protected override void OnDetachingFrom(T bindable)
{
base.OnDetachingFrom(bindable);
bindable.BindingContextChanged -= OnBindingContextChanged;
AssociatedObject = null;
}
void OnBindingContextChanged(object sender, EventArgs e)
{
OnBindingContextChanged();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
BindingContext = AssociatedObject.BindingContext;
}
}
}
using System;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace xxx
{
public class EventToCommandBehavior : BehaviorBase<View>
{
Delegate eventHandler;
public static readonly BindableProperty EventNameProperty = BindableProperty.Create("EventName", typeof(string), typeof(EventToCommandBehavior), null, propertyChanged: OnEventNameChanged);
public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create("CommandParameter", typeof(object), typeof(EventToCommandBehavior), null);
public static readonly BindableProperty InputConverterProperty = BindableProperty.Create("Converter", typeof(IValueConverter), typeof(EventToCommandBehavior), null);
public string EventName
{
get { return (string)GetValue(EventNameProperty); }
set { SetValue(EventNameProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public IValueConverter Converter
{
get { return (IValueConverter)GetValue(InputConverterProperty); }
set { SetValue(InputConverterProperty, value); }
}
protected override void OnAttachedTo(View bindable)
{
base.OnAttachedTo(bindable);
RegisterEvent(EventName);
}
protected override void OnDetachingFrom(View bindable)
{
DeregisterEvent(EventName);
base.OnDetachingFrom(bindable);
}
void RegisterEvent(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetRuntimeEvent(name);
if (eventInfo == null)
{
throw new ArgumentException(string.Format("EventToCommandBehavior: Can't register the '{0}' event.", EventName));
}
MethodInfo methodInfo = typeof(EventToCommandBehavior).GetTypeInfo().GetDeclaredMethod("OnEvent");
eventHandler = methodInfo.CreateDelegate(eventInfo.EventHandlerType, this);
eventInfo.AddEventHandler(AssociatedObject, eventHandler);
}
void DeregisterEvent(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
return;
}
if (eventHandler == null)
{
return;
}
EventInfo eventInfo = AssociatedObject.GetType().GetRuntimeEvent(name);
if (eventInfo == null)
{
throw new ArgumentException(string.Format("EventToCommandBehavior: Can't de-register the '{0}' event.", EventName));
}
eventInfo.RemoveEventHandler(AssociatedObject, eventHandler);
eventHandler = null;
}
void OnEvent(object sender, object eventArgs)
{
if (Command == null)
{
return;
}
object resolvedParameter;
if (CommandParameter != null)
{
resolvedParameter = CommandParameter;
}
else if (Converter != null)
{
resolvedParameter = Converter.Convert(eventArgs, typeof(object), null, null);
}
else
{
resolvedParameter = eventArgs;
}
if (Command.CanExecute(resolvedParameter))
{
Command.Execute(resolvedParameter);
}
}
static void OnEventNameChanged(BindableObject bindable, object oldValue, object newValue)
{
var behavior = (EventToCommandBehavior)bindable;
if (behavior.AssociatedObject == null)
{
return;
}
string oldEventName = (string)oldValue;
string newEventName = (string)newValue;
behavior.DeregisterEvent(oldEventName);
behavior.RegisterEvent(newEventName);
}
}
}
in your xaml
<Switch >
<Switch.Behaviors>
<local:EventToCommandBehavior EventName="Toggled" Command="{Binding ToggledCommand}"/>
</Switch.Behaviors>
</Switch>
And in your ViewModel
public class MyViewModel
{
public ICommand ToggledCommand { get; private set; }
public MyViewModel()
{
ToggledCommand = new Command(() => {
// do some thing you want
});
}
}
I bind a bool property on my viewmodel to the IsToggled property on the switch, then handle when this changes in the viewmodel.

EF SingleOrDefault doesn't work on ASP.NET

I've wrote some unit-tests for my project who tests my presenters, these presenters queries an EF context with SingleOrDefault, all the unit-tests are successful. But when I run my ASP.NET application I get continuously the error "'Single' not supported by Linq to Entities?" I want to know why this behavior is kicking in? I can't find any documentation about this behavior.
I use the following code:
Presenter:
public class ManagedQueryPresenter : BasePresenterMetModel<IManagedQueriesView, ManagedQueryBeheerModel>, IWebPartPresenter
{
public ManagedQueryPresenter(IManagedQueriesView view) : base(view, new ManagedQueryBeheerModel()) { }
#region IPagePresenter Members
public void OnViewInitialize()
{
}
public void OnViewInitialized()
{
}
public void OnViewLoaded()
{
}
#endregion
public void OnManagedQueriesSelecting()
{
View.ManagedQueries = Model.GetAll();
}
public void OnManagedQueryInserted(ManagedQuery entity)
{
Model.AddManagedQuery(entity);
View.ManagedQueries = Model.GetAll();
}
public void OnManagedQueryUpdated(ManagedQuery entity)
{
Model.UpdateManagedQuery(entity);
}
public void OnManagedQueryDeleted(ManagedQuery entity)
{
Model.DeleteManagedQuery(entity);
}
}
Model:
public class ManagedQueryBeheerModel : BaseModel, IModel
{
public void AddManagedQuery(ManagedQuery entity)
{
...
}
public void DeleteManagedQuery(ManagedQuery entity)
{
...
}
public void UpdateManagedQuery(ManagedQuery entity)
{
DoEntityAction<bool>(context =>
{
ManagedQuery toUpdate = context.ManagedQueries.Include(q => q.ManagedQueryParameters).SingleOrDefault(x => x.ID == entity.ID);
...
context.SaveChanges();
return true;
});
}
public IList<ManagedQuery> GetAll()
{
return DoRepositoryAction<ManagedQuery, List<ManagedQuery>>(repository => (List<ManagedQuery>)repository.GetAll());
}
public ManagedQuery Get(long ID)
{
return DoRepositoryAction<ManagedQuery, ManagedQuery>(repository => repository.GetSingleOrDefault(x => x.ID == ID));
}
}
UnitTest:
[TestMethod()]
public void OnManagedQueryUpdatedTest()
{
IManagedQueriesView view = new MockedManagedQueriesView();
ManagedQueryPresenter target = new ManagedQueryPresenter(view);
ManagedQuery entity = ManagedQueryHelper.CreateNewRecord(target.Model);
entity.Name += "Updated";
target.OnManagedQueryUpdated(entity);
}
public static class ManagedQueryHelper
{
public static ManagedQuery CreateNewRecord(ManagedQueryBeheerModel model)
{
ManagedQuery entity = new ManagedQuery
{
Description = "Test Query",
Name = "Test",
QueryText = #"SOME QUERY",
HasOutput = true,
Category = "Test",
};
model.AddManagedQuery(entity);
return entity;
}
}
ASP.NET View (Codebehind of ascx):
public partial class ManagedQueriesUserControl : WebPartMangedUserControlWithPresenter<ManagedQueryPresenter>, IManagedQueriesView
{
protected ASPxGridView _grid;
protected ObjectContainerDataSource _ocdsManagedQueries;
#region IServicesView Members
public IList<Entities.ManagedQuery> ManagedQueries
{
set
{
_grid.ForceDataRowType(typeof(ManagedQuery));
_ocdsManagedQueries.DataSource = value;
}
}
#endregion
protected void _ocdsManagedQueries_Deleted(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryDeleted((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Updated(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryUpdated((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Inserted(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceStatusEventArgs e)
{
Presenter.OnManagedQueryInserted((ManagedQuery)e.Instance);
}
protected void _ocdsManagedQueries_Selecting(object sender, Microsoft.Practices.Web.UI.WebControls.ObjectContainerDataSourceSelectingEventArgs e)
{
Presenter.OnManagedQueriesSelecting();
}
#region IWebPartView Members
public bool IsValid()
{
return Page.IsValid;
}
public string ErrorText
{
set { }
}
#endregion
}
I believe you can find the answer on this thread Error, method not supported by LINQ to Entities
I was forgotten that unittests are by default in VS2010 written in .NET 4 and my code in .NET3.5 so therefore it isn't working. In EF4 Single(OrDefault) is supported!

MVMLight Messaging and Silverlight

I am trying to get a sample to work using MVVM Light and the Messaging Class. In the sample, I have a test project created from the MVVM Template for Silveright 4. I have added a button on the main page. When the button is clicked, it updates a property on the ViewModel. When the property is updated, I want to show a messagebox with the new value.
The key line of code is:
Messenger.Default.Register(this, new Action(ShowMessage));
I can get this to work in WPF, but not silverlight. It should call ShowMessage with the string parameter when the property changes, but it does not. If I use:
Messenger.Default.Send("Hello MVVM");
This works and the string is sent as a message to ShowMessage.
However, the message does not get sent if the property changes, even though the property was created with the MVVMINPC snippet and has the following line:
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
This should have the same effect as Messager.Default.Send but it seems to be ignored. ThePropertyChangedEvent is indeed raised, but the messanger part seems to be disconnected.
Am I doing something wrong? Here is the full MainViewModel:
public class MainViewModel : ViewModelBase
{
public RelayCommand MyRelayCommand { get; set; }
public const string MyPropertyPropertyName = "MyProperty";
private string _myProperty = "test";
public string MyProperty
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
}
}
public void DoSomething()
{
//Messenger.Default.Send("Hello MVVM"); //Works
this.MyProperty = "Hello World"; //Doesn't work.
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Messenger.Default.Register(this, new Action<string>(ShowMessage));
MyRelayCommand = new RelayCommand(new Action(DoSomething));
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainViewModel_PropertyChanged);
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName);
}
}public class MainViewModel : ViewModelBase
{
public RelayCommand MyRelayCommand { get; set; }
public const string MyPropertyPropertyName = "MyProperty";
private string _myProperty = "test";
public string MyProperty
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
}
}
public void DoSomething()
{
//Messenger.Default.Send("Hello MVVM"); //Works
this.MyProperty = "Hello World"; //Doesn't work.
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Messenger.Default.Register(this, new Action<string>(ShowMessage));
MyRelayCommand = new RelayCommand(new Action(DoSomething));
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainViewModel_PropertyChanged);
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName);
}
}v
OK, I found that the Register line should look like this:
Messenger.Default.Register(this, new Action<PropertyChangedMessage<string>>(ShowMessage));
The point being there are different types of messages, and you have to register the PropertyChangedMessage type to recieve property changed messages.
Then also, the Action that recieves the message needs to take the correct parameter, like this:
public void ShowMessage(PropertyChangedMessage<string> e)
{
MessageBox.Show(e.NewValue.ToString());
}

Resources