CanExecute() public method

public CanExecute ( object parameter ) : bool
parameter object
return bool
Example #1
0
        public void TestExecute()
        {
            var    executedCount     = 0;
            string executedParameter = null;
            var    command           = new RelayCommand <string>(p =>
            {
                executedCount++;
                executedParameter = p;
            }, p => p == "Test");

            var canExecuteCount = 0;

            command.CanExecuteChanged += (sender, args) => { canExecuteCount++; };

            command.Execute("Test");

            Assert.AreEqual(1, executedCount);
            Assert.AreEqual("Test", executedParameter);
            Assert.AreEqual(1, canExecuteCount);

            Assert.IsTrue(command.CanExecute("Test"));
            Assert.IsFalse(command.CanExecute("Wrong parameter"));

            // Do not execute
            command.Execute("Wrong parameter");
            Assert.AreEqual(1, executedCount);

            command.InvalidateCanExecute();
            Assert.AreEqual(2, canExecuteCount);
        }
Example #2
0
        /// <summary>
        /// Sets a generic RelayCommand to an object and actuates the command when a specific event is raised. This method
        /// should be used when the event uses an EventHandler&lt;TEventArgs&gt;.
        /// </summary>
        /// <typeparam name="T">The type of the CommandParameter that will be passed to the RelayCommand.</typeparam>
        /// <typeparam name="TEventArgs">The type of the event's arguments.</typeparam>
        /// <param name="element">The element to which the command is added.</param>
        /// <param name="command">The command that must be added to the element.</param>
        /// <param name="eventName">The name of the event that will be subscribed to to actuate the command.</param>
        /// <param name="commandParameter">The command parameter that will be passed to the RelayCommand when it
        /// is executed. This is a fixed value. To pass an observable value, use one of the SetCommand
        /// overloads that uses a Binding as CommandParameter.</param>
        public static void SetCommand <T, TEventArgs>(
            this object element,
            string eventName,
            RelayCommand <T> command,
            T commandParameter)
        {
            var t = element.GetType();
            var e = t.GetEventInfoForControl(eventName);

            EventHandler <TEventArgs> handler = (s, args) => command.Execute(commandParameter);

            e.AddEventHandler(
                element,
                handler);

            var enabledProperty = t.GetProperty("Enabled");

            if (enabledProperty != null)
            {
                enabledProperty.SetValue(element, command.CanExecute(commandParameter));

                command.CanExecuteChanged += (s, args) => enabledProperty.SetValue(
                    element,
                    command.CanExecute(commandParameter));
            }
        }
        public void Test_RelayCommand_AlwaysEnabled()
        {
            int ticks = 0;

            var command = new RelayCommand(() => ticks++);

            Assert.IsTrue(command.CanExecute(null));
            Assert.IsTrue(command.CanExecute(new object()));

            (object, EventArgs)args = default;

            command.CanExecuteChanged += (s, e) => args = (s, e);

            command.NotifyCanExecuteChanged();

            Assert.AreSame(args.Item1, command);
            Assert.AreSame(args.Item2, EventArgs.Empty);

            command.Execute(null);

            Assert.AreEqual(ticks, 1);

            command.Execute(new object());

            Assert.AreEqual(ticks, 2);
        }
Example #4
0
        public void ExecuteCanExecuteTest()
        {
            var counter    = 0;
            var canExecute = true;

            try
            {
                Action <object> a = null;
                var             c = new RelayCommand(a);
                Assert.Fail("Should have thrown ArgumentNullException.", c);
            }
            catch (Exception e)
            {
                Assert.IsInstanceOf <ArgumentNullException>(e);
            }

            var command = new RelayCommand(param => counter++);

            Assert.IsTrue(command.CanExecute(new object()));
            command.Execute(new object());
            Assert.IsTrue(counter == 1);

            command = new RelayCommand(param => counter++, param => canExecute);
            Assert.IsTrue(command.CanExecute(new object()));
            command.Execute(new object());
            Assert.IsTrue(counter == 2);

            canExecute = false;
            Assert.IsFalse(command.CanExecute(new object()));
            command.Execute(new object());
            Assert.IsTrue(counter == 2);
        }
Example #5
0
        public void Test_RelayCommandOfT_AlwaysEnabled()
        {
            string text = string.Empty;

            var command = new RelayCommand <string>(s => text = s);

            Assert.IsTrue(command.CanExecute("Text"));
            Assert.IsTrue(command.CanExecute(null));

            Assert.ThrowsException <InvalidCastException>(() => command.CanExecute(new object()));

            (object, EventArgs)args = default;

            command.CanExecuteChanged += (s, e) => args = (s, e);

            command.NotifyCanExecuteChanged();

            Assert.AreSame(args.Item1, command);
            Assert.AreSame(args.Item2, EventArgs.Empty);

            command.Execute("Hello");

            Assert.AreEqual(text, "Hello");

            command.Execute(null);

            Assert.AreEqual(text, null);
        }
Example #6
0
        public void CanCallCanExecute()
        {
            var parameter = new object();
            var result    = _testClass.CanExecute(parameter);

            Assert.Fail("Create or modify test");
        }
Example #7
0
        public void TestCanExecute_WithPredicate()
        {
            Predicate <object> p = (o) => { return((bool)o); };
            RelayCommand       c = new RelayCommand((o) => { }, p);

            Assert.IsFalse(c.CanExecute(false));
            Assert.IsTrue(c.CanExecute(true));
        }
Example #8
0
        public void SingleArgumentConstructor_CanExecute_ReturnsTrueAlways()
        {
            Action <object> execute = (o => { });
            var             target  = new RelayCommand(execute);

            target.CanExecute(null).Should().BeTrue();
            target.CanExecute(true).Should().BeTrue();
            target.CanExecute(false).Should().BeTrue();
        }
Example #9
0
        public void CanExecuteTest()
        {
            var command = new RelayCommand <string>(p =>
            {
            },
                                                    p => p == "CanExecute");

            Assert.AreEqual(true, command.CanExecute("CanExecute"));
            Assert.AreEqual(false, command.CanExecute("Hello"));
        }
Example #10
0
        public static UIButton SetCommand(this UIButton control, RelayCommand command)
        {
            control.TouchUpInside += (s, e) => { };

            control.SetCommand(Events.TouchUpInside, command);
            control.Enabled            = command.CanExecute(null);
            command.CanExecuteChanged += (s, args) => control.Enabled = command.CanExecute(null);

            return(control);
        }
Example #11
0
        public void CanExecuteReturnsPredicateValue()
        {
            var cmd = new RelayCommand(Helpers.DoNothingAction, p => (bool)p);

            var canExecuteTrue  = cmd.CanExecute(true);
            var canExecuteFalse = cmd.CanExecute(false);

            Assert.IsTrue(canExecuteTrue);
            Assert.IsFalse(canExecuteFalse);
        }
Example #12
0
        public void CanExecute_ReturnsFalse_ReturnsFalseAlways()
        {
            Predicate <object> canExecute = (o => false);
            Action <object>    execute    = (o => { });
            var target = new RelayCommand(execute, canExecute);

            target.CanExecute(null).Should().BeFalse();
            target.CanExecute(true).Should().BeFalse();
            target.CanExecute(false).Should().BeFalse();
        }
Example #13
0
        public void TestActionGenericPredicateConstructor()
        {
            var n = 0;
            Predicate <object> predicate = obj => obj is int;
            var command = new RelayCommand(execute: num => n = (int)num, canExecute: predicate);

            Assert.IsTrue(condition: command.CanExecute(parameter: 1), message: "Should be able to execute for int");
            command.Execute(parameter: 1);
            Assert.AreEqual(expected: 1, actual: n, message: "Action did not run.");
            Assert.IsFalse(condition: command.CanExecute(parameter: null), message: "Allows to run for non-int");
        }
Example #14
0
        public void CanExecute_ParamTest()
        {
            RelayCommand target = new RelayCommand((p) =>
            {
            }, (p) => { return((bool)p); });

            Assert.IsTrue(target.CanExecute(true));

            Assert.IsFalse(target.CanExecute(false));

            Assert.IsTrue(target.CanExecute(true));
        }
Example #15
0
        public void CanExecuteUsesPredicateIfSet()
        {
            var canExecute = false;

// ReSharper disable once AccessToModifiedClosure
            var command = new RelayCommand(o => { }, o => canExecute);

            command.CanExecute(null).Should().BeFalse();

            canExecute = true;

            command.CanExecute(null).Should().BeTrue();
        }
Example #16
0
        public void CanExecuteUsesPredicateIfSet()
        {
            var canExecute = false;

            // ReSharper disable once AccessToModifiedClosure
            var command = new RelayCommand(o => { }, o => canExecute);

            command.CanExecute(null).Should().BeFalse();

            canExecute = true;

            command.CanExecute(null).Should().BeTrue();
        }
Example #17
0
        /// <summary>
        /// Sets a generic RelayCommand to an object and actuate the command when a specific event is raised. This method
        /// can only be used when the event uses a standard EventHandler.
        /// </summary>
        /// <typeparam name="T">The type of the CommandParameter that will be passed to the RelayCommand.</typeparam>
        /// <param name="element">The element to which the command is added.</param>
        /// <param name="eventName">The name of the event that will be subscribed to to actuate the command.</param>
        /// <param name="command">The command that must be added to the element.</param>
        /// <param name="commandParameterBinding">A <see cref="Binding{T, T}">Binding</see> instance subscribed to
        /// the CommandParameter that will passed to the RelayCommand. Depending on the Binding, the CommandParameter
        /// will be observed and changes will be passed to the command, for example to update the CanExecute.</param>
        public static void SetCommand <T>(
            this object element,
            string eventName,
            RelayCommand <T> command,
            Binding commandParameterBinding = null)
        {
            var castedBinding = (Binding <T, T>)commandParameterBinding;

            var t = element.GetType();
            var e = t.GetEvent(eventName);

            if (e == null)
            {
                throw new ArgumentException("Event not found: " + eventName, "eventName");
            }

            EventHandler handler = (s, args) =>
            {
                var param = castedBinding == null ? default(T) : castedBinding.Value;

                if (command.CanExecute(param))
                {
                    command.Execute(param);
                }
            };

            e.AddEventHandler(
                element,
                handler);

            if (commandParameterBinding == null)
            {
                return;
            }

            var enabledProperty = t.GetProperty("Enabled");

            if (enabledProperty != null)
            {
                enabledProperty.SetValue(element, command.CanExecute(castedBinding.Value));

                commandParameterBinding.ValueChanged += (s, args) => enabledProperty.SetValue(
                    element,
                    command.CanExecute(castedBinding.Value));

                command.CanExecuteChanged += (s, args) => enabledProperty.SetValue(
                    element,
                    command.CanExecute(castedBinding.Value));
            }
        }
Example #18
0
        public void TheExecutionStatusLogicDeterminesWhetherTheRelayCommandCanExecuteInItsCurrentState()
        {
            bool                   canExecute = false;
            IInputCommand          command    = new RelayCommand(() => { }, () => canExecute);
            IInputCommand <string> commandT   = new RelayCommand <string>(_ => { }, _ => canExecute);

            Assert.False(command.CanExecute());
            Assert.False(commandT.CanExecute("F0"));

            canExecute = true;

            Assert.True(command.CanExecute());
            Assert.True(commandT.CanExecute("F0"));
        }
        public void RelayCommand_ConditionalExecutionTests()
        {
            int          initVal     = 0;
            int          invalidVal  = 5;
            int          validVal    = 1;
            int          expectedVal = 10;
            RelayCommand command     = new RelayCommand((x => initVal = (int)x), (x => (int)x != invalidVal));

            Assert.AreEqual(0, initVal, "testVal was not initialized to the expected value");
            Assert.AreEqual(false, command.CanExecute(invalidVal), "CanExecute did not return false for an invalid value");
            Assert.AreEqual(true, command.CanExecute(validVal), "CanExecute did not return true for a valid value");
            command.Execute(expectedVal);
            Assert.AreEqual(10, initVal, "Relay command did not execute appropriately");
        }
Example #20
0
        public void TestActionFuncConstructor()
        {
            var n          = 0;
            var canExecute = false;
            var command    = new RelayCommand(execute: () => ++ n, canExecute: () => canExecute);

            Assert.IsFalse(condition: command.CanExecute(parameter: null), message: "Can execute was set to false.");

            canExecute = true;
            command.OnCanExecuteChanged();

            Assert.IsTrue(condition: command.CanExecute(parameter: null), message: "Can execute was set true.");
            command.Execute(parameter: null);
            Assert.AreEqual(expected: 1, actual: n, message: "Action did not execute.");
        }
Example #21
0
        public void TestCanExecute()
        {
            var canExecute = true;

            var command = new RelayCommand(() =>
            {
            },
                                           () => canExecute);

            Assert.AreEqual(true, command.CanExecute(null));

            canExecute = false;

            Assert.AreEqual(false, command.CanExecute(null));
        }
Example #22
0
        public void CanExecute_MethodTest()
        {
            bool         canExecute = true;
            RelayCommand target     = new RelayCommand((p) =>
            {
            }, (p) => { return(canExecute); });

            Assert.IsTrue(target.CanExecute(null));

            canExecute = false;
            Assert.IsFalse(target.CanExecute(null));

            canExecute = true;
            Assert.IsTrue(target.CanExecute(null));
        }
Example #23
0
        public void RelayCommandTest()
        {
            var validate = false;
            var command  = new RelayCommand <bool>(b => validate = b, b => validate != b);

            command.CanExecuteChanged += Command_CanExecuteChanged; // for code coverage

            Assert.IsTrue(command.CanExecute(!validate));
            command.Execute(true);

            Assert.IsFalse(command.CanExecute(validate));
            Assert.IsTrue(validate);

            command.CanExecuteChanged -= Command_CanExecuteChanged; // for code coverage
        }
 private void PortSelectionCommitted(object sender, System.EventArgs e)
 {
     if (SelectPortCommand.CanExecute(this))
     {
         SelectPortCommand.Execute(this);
     }
 }
Example #25
0
        public void Given_RelayCommand_With_CanExecute_Should_Return_BasedOnPredicate()
        {
            ICommand command = new RelayCommand((m) => { }, (m) => false);

            var actual = command.CanExecute(null);
            actual.Should().BeFalse();
        }
		public void RelayCommand_CanExecute_CanNotExecuteWhenFalse()
		{
			var count = 0;
			var cmd = new RelayCommand(o => count = (int) o, () => false);

			Assert.IsFalse(cmd.CanExecute());
		}
Example #27
0
        public void TestActionPredicateConstructor()
        {
            var n = 0;
            Predicate <object> predicate = obj => obj is int && ((int)obj == 0);
            var command = new RelayCommand(execute: () => ++ n, canExecute: predicate);

            Assert.IsTrue(condition: command.CanExecute(n),
                          message: "Should be able to execute for n equal zero.");

            command.Execute(parameter: null);
            command.OnCanExecuteChanged();

            Assert.AreEqual(expected: 1, actual: n, message: "Action did not execute.");
            Assert.IsFalse(condition: command.CanExecute(n),
                           message: "Should not be able to execute for n equal to 1.");
        }
Example #28
0
        public void RelayCommandCanExecuteTest()
        {
            int          _ExecuteCount           = 0;
            bool         _CanExecute             = true;
            int          _CanExecuteChangedCount = 0;
            RelayCommand _testCommand            = new RelayCommand(() => _ExecuteCount++, () => _CanExecute);

            _testCommand.CanExecuteChanged += (object sender, EventArgs e) => _CanExecuteChangedCount++;
            Assert.IsTrue(_testCommand.CanExecute(null));
            _testCommand.Execute(null);
            _CanExecute = false;
            Assert.IsFalse(_testCommand.CanExecute(null));
            _testCommand.Execute(null);
            Assert.AreEqual <int>(2, _ExecuteCount);
            Assert.AreEqual <int>(0, _CanExecuteChangedCount);
        }
Example #29
0
        private void ExecuteAddStoryCommand()
        {
            if (!AddStoryCommand.CanExecute(null))
            {
                return;
            }

            if (Stories == null)
            {
                Stories = new ObservableCollection <Story>();
            }

            Stories.Add(new Story
            {
                Title    = Title,
                ImageUrl = ImageUrl,
                EntryUrl = EntryUrl,
                BodyHtml = BodyHtml
            });

            Title    = "";
            ImageUrl = "";
            EntryUrl = "";
            BodyHtml = "";
        }
Example #30
0
        private void ExecuteCopyPostToClipboardCommand()
        {
            if (!CopyPostToClipboardCommand.CanExecute(null))
            {
                return;
            }

            var post = new StringBuilder();

            post.AppendLine("<p>[intro]</p> <dl class=\"twoCol\">");

            foreach (var story in Stories)
            {
                post.AppendLine("<dt>");
                post.AppendFormat("<a href=\"{0}\" target=\"_blank\"><img border=\"0\" alt=\"\" src=\"{1}\" width=\"220\" height=\"123\"></a> ", story.EntryUrl, story.ImageUrl);
                post.AppendLine("</dt>");
                post.AppendLine("<dd>");
                post.AppendFormat("<a href=\"{0}\"><strong>{1}</strong></a>", story.EntryUrl, story.Title);
                post.AppendLine("</dd>");
                post.AppendLine("<dd>");
                post.AppendFormat("<p>{0}</p>", story.BodyHtml);
                post.AppendLine("</dd>");
            }

            post.AppendLine("</dl>");
            post.AppendLine("<p><a class=\"twitter-follow-button\" href=\"https://twitter.com/ch9\">Follow @CH9</a> <br />");
            post.AppendLine("<a class=\"twitter-follow-button\" href=\"https://twitter.com/gduncan411\">Follow @gduncan411</a></p>");

            ClipboardHelper.CopyHtmlToClipBoard(post.ToString());
            MessageBox.Show("Copied");
        }
        private void ExecuteLoginCommand()
        {
            if (!LoginCommand.CanExecute(null))
            {
                return;
            }
            // Verifique las credenciales del usuario están vacías o no.
            if (!string.IsNullOrEmpty(this.UserPrincipalName) && !string.IsNullOrEmpty(this.UserPassword))
            {
                // Asignar nombre de usuario y clave para variable.
                UserCredential.UserName = UserPrincipalName;
                UserCredential.Password = StringExtensions.ToSecureString(UserPassword);

                SavePropertiesSettings();

                MsolCmdletWrapper.Instance.Connect();

                if (MsolCmdletWrapper.Instance.IsConnect)
                {
                    Messenger.Default.Send(true);
                }
                else
                {
                    UserPassword = string.Empty;
                    MessageBox.Show(Messages.BadMemberNameOrPassword);
                }
            }
        }
Example #32
0
 public static void ExecuteRelayCommand(RelayCommand command)
 {
     if (command.CanExecute(null))
     {
         command.Execute(null);
     }
 }
		public void RelayCommand_CanExecute_CanExecuteWhenTrue()
		{
			var count = 0;
			var cmd = new RelayCommand(o => count = (int) o, () => true);

			Assert.IsTrue(cmd.CanExecute());
		}
        public void CanExecuteIsTrueWhenThereIsNoPredicate()
        {
            _relayCommand = new RelayCommand(OnActionCalled);

            var actual = _relayCommand.CanExecute(null);

            Assert.IsTrue(actual);
        }
Example #35
0
        public void Given_CanExecuteDelegate_When_ICallCanExecute_ItReturnsCorrectValue()
        {
            var expected = new Random().Next(0, 2) == 1;

            var sut = new RelayCommand<object>(Delegate1, o => expected);

            Assert.AreEqual(expected, sut.CanExecute(null));
        }
		public void RelayCommand_Construction_WithoutCanExecuteCanActuallyExecute()
		{
			var count = 0;
			var cmd = new RelayCommand(o => count = (int) o);

			if (cmd.CanExecute())
				cmd.Execute(15);

			Assert.AreEqual(15, count);
		}
Example #37
0
 public void Given_NoCanExecute_When_AskedForCanExecute_CanExecuteReturnsTrue()
 {
     var sut = new RelayCommand<object>(Delegate1);
     Assert.IsTrue(sut.CanExecute(null));
 }
Example #38
0
 public void CanExecuteIsTrueIfNotSet()
 {
     var command = new RelayCommand(o => { });
     command.CanExecute(null).Should().BeTrue();
 }
Example #39
0
        private void AddCommandToService(OleMenuCommandService service, Guid cmdSet, int cmdId, RelayCommand relayCommand)
        {
            var commandId = new CommandID(cmdSet, cmdId);
            var menuCommand = new OleMenuCommand((sender, args) =>
            {
                relayCommand.Execute(null);
            }, commandId);

            menuCommand.BeforeQueryStatus += (sender, args) =>
            {
                menuCommand.Enabled = relayCommand.CanExecute(null);
            };

            service.AddCommand(menuCommand);
        }