mvvm与canexecute和绑定命令混淆

时间:2013-07-17 19:07:45

标签: c# wpf mvvm

我非常难以绕过关于这个主题的教程和帖子中的逻辑。我试图在我编写的wpf应用程序中实现它。

基本上,我使用列表框在列表中显示对象的ToString,并允许用户通过添加和删除按钮从该列表及其相应的列表框中添加和删除。我遇到的问题是执行“删除”按钮。如果没有选择列表框项,我想要禁用该按钮,这是该模式适合的事情之一。我对如何实施这一条件感到很遗憾。

此时,当我突出显示列表框项目时,该按钮未启用。我想CanExecuteChanged事件没有解雇..我该如何更改?

我的CommandsHandler类:

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

namespace TechopsTools
{

    public class CommandHandler : ICommand
    {
        private Action<object> _execute;
        private bool _canExecute;

        public CommandHandler(Action<object> execute)
            : this(execute, true)
        {
        }

        public CommandHandler(Action<object> execute, bool canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            _execute = execute;
            _canExecute = canExecute;
        }


        public bool CanExecute(object parameter)
        {
            return _canExecute;
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

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

}

我的viewmodel:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Input;

namespace TechopsTools
{
    class LogCheckClientViewModel : INotifyPropertyChanged
    {
        private string uri;
        private string response;
        private bool _canRemove;
        private LogConstraints selectedConstraints;

        private ObservableCollection<LogConstraints> constraints;

        public event PropertyChangedEventHandler PropertyChanged;

        public LogConstraints SelectedConstraints
        {
            get
            {
                return selectedConstraints;
            }
            set
            {
                selectedConstraints = value;
                OnPropertyChanged("SelectedConstraints");
            }
        }

        private CommandHandler removeItemCommand;
        public ICommand RemoveItemCommand
        {
            get
            {
                if (removeItemCommand == null)
                    removeItemCommand = new CommandHandler(param => RemoveConstraint(), SelectedConstraints != null);
                return removeItemCommand;
            }
        }

        public string Response 
        {
            get
            {
                return response;
            }
            set
            {
                response = value;
                OnPropertyChanged("Response");
            }
        }

        public string Uri
        {
            get
            {
                return uri;
            }
            set
            {
                uri = value;
                OnPropertyChanged("Uri");
            }
        }

        public ObservableCollection<LogConstraints> Constraints
        {
            get
            {
                return constraints;
            }
            set
            {
                constraints = value;
                OnPropertyChanged("Constraints");
            }
        }

        public LogCheckClientViewModel()
        {
            constraints = new ObservableCollection<LogConstraints>();
        }

        public void AddConstraint()
        {
            NewConstraint newConstraint = new NewConstraint();
            newConstraint.ShowDialog();
            if (newConstraint._vm.constraint != null)
            {
                constraints.Add(newConstraint._vm.constraint);
            }
        }

        private void RemoveConstraint()
        {
            Constraints.Remove(SelectedConstraints);
            OnPropertyChanged("Constraints");
        }

XAML:

<Window x:Class="TechopsTools.LogCheckClient"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:TechopsTools"
        Title="LogCheck" Height="453.057" Width="495.986">
    <Grid>
        <TextBox Text="{Binding Response}" HorizontalAlignment="Left" Height="128" Margin="38,212,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="413" VerticalScrollBarVisibility="Auto" IsEnabled="False"/>
        <Label Content="Response" HorizontalAlignment="Left" Margin="38,188,0,0" VerticalAlignment="Top" Width="78" Height="24"/>
        <TextBox Text="{Binding Uri}" HorizontalAlignment="Left" Height="23" Margin="38,26,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="413"/>
        <Label Content="Uri" HorizontalAlignment="Left" Margin="38,0,0,0" VerticalAlignment="Top" Width="78" Height="24"/>
        <Button Content="Add Constraint" HorizontalAlignment="Left" Margin="38,54,0,0" VerticalAlignment="Top" Width="127" Height="56" Click="Add_Click"/>
        <Button x:Name="Submit" Content="Submit Request" HorizontalAlignment="Left" Margin="38,345,0,0" VerticalAlignment="Top" Width="413" Height="70" Click="Submit_Click"/>
        <ListBox SelectedItem="{Binding Path=SelectedConstraints,UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding Constraints}" HorizontalAlignment="Left" Height="124" Margin="182,54,0,0" VerticalAlignment="Top" Width="269">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=description}" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Command="{Binding RemoveItemCommand}" Content="Remove Constraint" HorizontalAlignment="Left" Margin="38,122,0,0" VerticalAlignment="Top" Width="127" Height="56" />
    </Grid>
</Window>

2 个答案:

答案 0 :(得分:4)

您确实需要使用CanExecute委托,就像使用Execute处理程序一样。

现在基本上你正在检查它是否可以在首次访问RemoveItemCommand时执行。但是它只是保持整个时间的价值。

如果传入一个具有相同条件的委托(可能为空列表添加,而不仅仅是空列表),我打赌它会起作用。

换句话说,在CommandHandler中,更改

private bool _canExecute;

private Func<bool,object> _canExecute;

并更改

public bool CanExecute(object parameter)
{
    return _canExecute;
}

public bool CanExecute(object parameter)
{
    return _canExecute(parameter);
}

然后在ViewModel中,更改

removeItemCommand = new CommandHandler(param => RemoveConstraint(), 
                                       SelectedConstraints != null);

removeItemcommand = new CommandHandler(param => RemoveConstraint(), 
                                       param => SelectedConstraints != null);

(请注意,这可能不是完全正确的代码,因为我只是徒手写,但希望你明白这一点)

答案 1 :(得分:0)

我认为可以在XAML文件中完成,只需使用DataTrigger。

如果这个解决方案让您满意,请告诉我写评论,我会为您提供一些代码。

祝你好运