簡體   English   中英

按鈕上的綁定命令不起作用wpf mvvm

[英]Binding command on button doesn't work wpf mvvm

我正在嘗試向數據庫表單創建簡單的添加實體,但是綁定命令不起作用,我不知道為什么。 這是XAML

<DockPanel Margin="30">
    <StackPanel DockPanel.Dock="Top">
        <Label>Manufacturer</Label>
        <TextBox Text="{Binding Manufacturer, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />
        <Label>Type</Label>
        <TextBox Text="{Binding Type, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />
        <Label>Serial number</Label>
        <TextBox Text="{Binding SerialNumber, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}" />
        <Button Command="{Binding AddScaleCommand}">Add Scale</Button>
    </StackPanel>
    <ListBox ItemsSource="{Binding Scales}" DockPanel.Dock="Bottom"></ListBox>
</DockPanel>

這是命令所在的ScaleViewModel

public class ScaleViewModel : ViewModel
{
    public ScaleViewModel()
    {
        Scales = new ObservableCollection<Scale>();
    }

    public ICollection<Scale> Scales { get; private set; }
    public string Manufacturer { get; set; }
    public string Type { get; set; }

    public string SerialNumber { get; set; }

    public bool IsValid
    {
        get
        {
            return !string.IsNullOrWhiteSpace(SerialNumber);
        }
    }

    public ActionCommand AddScaleCommand
    {
        get
        {
            return new ActionCommand(p => AddScale(Manufacturer, Type, SerialNumber), 
                                    p => IsValid);
        }
    }

    private void AddScale(string manufacturer, string type, string serialNumber)
    {
        using (var api = new BusinessContext())
        {
            var scale = new Scale
            {
                Manifacturer = manufacturer,
                Type = type,
                SerialNumber = serialNumber
            };
            try
            {
                api.AddNewScale(scale);
            }
            catch (Exception ex)
            {
                //TODO kasnije
                return;
            }

            Scales.Add(scale);
        };
    }
}

Scale是具有3個屬性(制造商,類型和序列號)的簡單類,ViewModel類實現INotifyPropertyChanged和IDataErrorInfo並實現必需的方法。 ActionCommand類實現ICommand並實現ICommand方法。

UPDATE添加了ActionCommand類

public class ActionCommand : ICommand
{
    private readonly Action<Object> action;
    private readonly Predicate<Object> predicate;

    public ActionCommand(Action<Object> action) : this(action, null)
    {

    }

    public ActionCommand(Action<Object> action, Predicate<Object> predicate)
    {
        if (action == null)
        {
            throw new ArgumentNullException("Action", "Yout must specify an Action<T>");
        }

        this.action = action;
        this.predicate = predicate;
    }

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        if (predicate == null)
        {
            return true;
        }

        return predicate(parameter);
    }

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

    public void Execute()
    {
        Execute(null);
    }

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

    #endregion
}

您的ViewModel類需要實現IDataErrorInfo和INotifyPropertyChanged才能使驗證生效

此外,在更改SerialNumber后,ActionCommand似乎沒有任何方法可以重新評估IsValid()。

有關使用IDataErrorInfo在WPF / MVVM中進行數據驗證的更多詳細信息,請參閱我的博客文章

問題是我沒有在App.xaml.cs中將DataContext添加到MainWindow中

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        var window = new MainWindow
        {
            DataContext = new ScaleViewModel()
        };

        window.ShowDialog();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM