Кнопка не отключается, если инициирующее событие приходит из-под контроля в другом кадре - PullRequest
0 голосов
/ 08 мая 2019

Я пытаюсь отключить кнопку с помощью команд, когда текстовое поле пусто.Структура интерфейса:MainWindow.xaml - содержит кнопку, которую необходимо отключить.page.xaml - страница, отображаемая в рамке в главном окне.

XAML:

<Window x:Class="CommandButtons.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:CommandButtons"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:WindowVM/>
    </Window.DataContext>
    <Grid>
        <Button Content="Button" Command="{Binding LaunchButtonAction}"  HorizontalAlignment="Left" Margin="555,80,0,0" VerticalAlignment="Top" Width="75" Height="40"/>
        <TextBox HorizontalAlignment="Left"  Height="65" Margin="80,120,0,0" TextWrapping="Wrap" Text="{Binding TextSource,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="245"/>
    </Grid>
</Window>

Модель представления:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace CommandButtons
{
    class WindowVM
    {
        private string textSource;

        public string TextSource
        {
            get { return textSource; }
            set
            {
                textSource = value;
                if(textSource.Length==0)
                {
                    canExecute = false;
                }else
                {
                    canExecute = true;
                }
            }
        }


        private ICommand launchButtonAction;
        public ICommand LaunchButtonAction
        {
            get { return launchButtonAction; }
            set { launchButtonAction = value; }
        }

        private ICommand enableDisable;

        public ICommand EnableDisable
        {
            get { return enableDisable; }
            set { enableDisable = value; }
        }


        private bool canExecute = false;
        public bool CanExecute
        {
            get { return canExecute; }
            set
            { if(canExecute==value)
                { return; }
                canExecute = value;
            }
        }

        public WindowVM()
        {
            LaunchButtonAction = new RelayCommand(ShowMessage, param => this.canExecute);
           // EnableDisable = new RelayCommand(SwitchOnOff);
        }


        private void ShowMessage(object obj)
        {
            MessageBox.Show("enabled");
        }
    }
}

RelayComand:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace CommandButtons
{
    class RelayCommand : ICommand
    {
        private Action<object> execute;
        private Predicate<object> canExecute;
        private event EventHandler canExecuteChangedInternal;

        public RelayCommand(Action<object> execute)
            :this(execute, DefaultCanExecute)
        {

        }

        public RelayCommand(Action<object> execute,Predicate<object> canExecute)
        {
            this.execute = execute;
            this.canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
                this.canExecuteChangedInternal += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
                this.canExecuteChangedInternal -= value;
            }
        }

        public bool CanExecute(object parameter)
        {
            return this.canExecute != null && this.canExecute(parameter);
        }

        public void Execute(object parameter)
        {
            this.execute(parameter);
        }

        public void OnCanExecuteChanged()
        {
            EventHandler handler = this.canExecuteChangedInternal;
            if(handler!=null)
            {
                handler.Invoke(this, EventArgs.Empty);
            }
        }

        public void Destroy()
        {
            this.canExecute = _ => false;
            this.execute = _ => { return; };
        }

        private static bool DefaultCanExecute(object parameter)
        {
            return true;
        }
    }
}

На самом деле я обнаружил, что если я прикреплю команду к кнопке на странице - эта кнопка будет отключена, а первая останется включенной.

Сильно запутался.Любая помощь приветствуется!

...