c# - 与 ICommand 的 WPF 绑定(bind)错误

标签 c# wpf xaml data-binding

我有一个简单的 WPF 示例,试图将 ListBox 的 Selected 事件绑定(bind)到 View 模型中的 ICommand。

XAML

<Window x:Class="WpfApp1.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"
        mc:Ignorable="d">
    <Grid>
        <ListBox ItemsSource="{Binding Items}" 
                 Selected="{Binding DoSomething}"/>

    </Grid>
</Window>

查看模型

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new ViewModel();
        }
    }

    public class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            Items = new List<string>();
            Items.Add("A");
            Items.Add("B");
            Items.Add("C");

            DoSomething = new MyCommand();
        }

        public List<string> Items { get; set; }


        public event PropertyChangedEventHandler PropertyChanged;

        public ICommand DoSomething { get; set; }
    }

    public class MyCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;

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

        public void Execute(object parameter) { }
    }
}

错误发生在 InitializeComponent 的构造函数中。

XamlParseException: A 'Binding' cannot be set on the 'AddSelectedHandler' property of type 'ListBox'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.

enter image description here

如何从 ListBox 控件的 Selected 事件在我的 View 模型中调用 ICommand?

最佳答案

在 ListBox 上选择是一个事件。您有 SelectedItem,您可以将其绑定(bind)到与 View 模型上列表元素相同类型的属性:

<Grid>
    <ListBox ItemsSource="{Binding Items}" 
             SelectedItem="{Binding MyItem}"/>
</Grid>

.

public class ViewModel : INotifyPropertyChanged
{
    public string MyItem { get; set; }
}

至于您的命令,您需要一个处理 CommandSource 的控件,例如 Button:

<Button Command="{Binding DoSomething}" CommandParameter="{Binding}" />

像这样绑定(bind)它,将使 WPF 能够识别您的 ICommand。 CommandParameter 是可选的。

关于c# - 与 ICommand 的 WPF 绑定(bind)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49501216/

相关文章:

c# - 帮助 Linq 查询

c# - 流式wcf结束后如何删除文件

javascript - 如何重置 UWP WebView 的内容缩放因子

WPF Prism - 使用 IConfirmNavigationRequest 防止选项卡切换不起作用

c# - 如何在 WPF 中创建类似 Windows 8 样式的进度环?

xaml - Windows Phone 8 TextBlock 切断 XAML 中的文本

c# - 无法确定 OR “Value cannot be null, parameter name ' 键的主体端'”

wpf - 绑定(bind)时如何在xaml中进行计算?

c# - WPF MVVM UI如果线程阻塞则不更新

c# - 基于绑定(bind)对象和模型属性的可见绑定(bind)