传递动态按钮的参数 - MVVM Light

问题描述 投票:-1回答:1

以下代码动态地成功创建了两个按钮,我无法弄清楚如何在单击时使按钮打开不同的文件。

我错过了什么?

XAML:

<ItemsControl ItemsSource="{Binding DataButtons}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Button Content="{Binding ButtonName}" 
                    Command="{Binding ButtonCommand}"
                    CommandParameter="{Binding FilePath}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

ViewModel:

namespace DynamicControlsMvvmLight.ViewModel
{
    public class MainViewModel : ViewModelBase
    {
        private readonly ObservableCollection<ButtonModel> _dataButtons = new ObservableCollection<ButtonModel>();
        public ObservableCollection<ButtonModel> DataButtons { get { return _dataButtons; } }

        private ICommand _buttonCommand;
        public ICommand ButtonCommand
        {
            get {
                if (_buttonCommand == null) {
                    _buttonCommand = new RelayCommand<object>(CommandExecute, CanCommandExecute);
                }
                return _buttonCommand;
            }
        }

        public MainViewModel()
        {
            ButtonModel data1 = new ButtonModel("Button 1", ButtonCommand, "c:/Folder/File1.PDF");
            ButtonModel data2 = new ButtonModel("Button 2", ButtonCommand, "c:/Folder/File2.PDF");
            DataButtons.Add(data1);
            DataButtons.Add(data2);
        }

        private void CommandExecute(object FilePath)
        {
            ButtonModel button = FilePath as ButtonModel;
            System.Diagnostics.Process.Start(button.FilePath);
        }

        private bool CanCommandExecute(object FilePath)
        {
            Console.WriteLine("CanCommandExecute Method...");
            return true;
        }
    }
}

Model:

namespace DynamicControlsMvvmLight.Model
{
    public class ButtonModel
    {
        public string ButtonName { get; set; }
        public ICommand ButtonCommand { get; set; }
        public string FilePath { get; set; }

        public ButtonModel(string buttonName, ICommand buttonCommand, string filePath)
        {
            ButtonName = buttonName;
            ButtonCommand = buttonCommand;
            FilePath = filePath;
        }
    }
}

ERROR

单击任何按钮时出现以下错误。 enter image description here

c# wpf mvvm data-binding mvvm-light
1个回答
1
投票

RelayCommand希望收到CommandParameter,在这种情况下是string

代码必须如下所示:

        public ICommand ButtonCommand
        {
            get
            {
                if (_buttonCommand == null)
                {
                    _buttonCommand = new RelayCommand<string>(CommandExecute, CanCommandExecute);
                }
                return _buttonCommand;
            }
        }

        private void CommandExecute(string filePath)
        {
            System.Diagnostics.Process.Start(filePath);
        }
© www.soinside.com 2019 - 2024. All rights reserved.