简体   繁体   English

无法绑定到我的自定义控件中的命令

[英]Can't bind to a command in my custom control

I created a control based of TextBox that looks like this: 我创建了一个基于TextBox的控件,如下所示:

public class DelayedTextBox : TextBox
{
    public ICommand DelayedTextChangedCommand
    {
        get;
        set;
    }
}

I then create Foo.xaml with the following code: 然后,我使用以下代码创建Foo.xaml:

<h:DelayedTextBox DelayedTextChangedCommand="{Binding FooCommand}"/>

And I have FooViewModel (which is hooked up correctly in the XAML because other parts can bind to properties in FooViewModel) that has this: 我有FooViewModel(它在XAML中正确连接,因为其他部分可以绑定到FooViewModel中的属性)具有:

private ICommand _fooCommand;
    public ICommand FooCommand
    {
        get
        {
            if (_fooCommand == null)
            {
                _fooCommand = new RelayCommand(CheckFoo, () => CanExecuteFooCheck());
            }

            return _fooCommand;
        }
    }

I am using RelayCommand from GalaSoft.MvvmLight, which works for other commands in my project 我正在使用GalaSoft.MvvmLight的RelayCommand,它适用于我项目中的其他命令

When I run my project, I get the following error when Foo.xaml gets loaded: 当我运行我的项目时,我在加载Foo.xaml时收到以下错误:

WinRT information: Failed to assign to property 'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. WinRT信息:无法分配给属性'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'。 [Line: 29 Position: 103] An exception of type 'Windows.UI.Xaml.Markup.XamlParseException' occurred in TestApp.exe but was not handled in user code WinRT information: Failed to assign to property 'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. [行:29位置:103] TestApp.exe中出现“Windows.UI.Xaml.Markup.XamlParseException”类型的异常,但未在用户代码WinRT信息中处理:无法分配给属性'TestApp.Helpers.DelayedTextBox。 DelayedTextChangedCommand”。 [Line: 29 Position: 103] The text associated with this error code could not be found. [行:29位置:103]找不到与此错误代码关联的文本。

Failed to assign to property 'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. 无法分配给属性'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'。 [Line: 29 Position: 103] [线路:29位置:103]

I'm super confused as to why it can't bind properly, what am I doing wrong? 我非常困惑为什么它不能正确绑定,我做错了什么?

The issue was I didn't add a dependencyProperty as @Lynn Crumbling mentioned in the comments to my question. 问题是我没有在我的问题的评论中提到的@Lynn Crumbling中添加了dependencyProperty。

Adding the following to DelayedTextBox did the trick: 将以下内容添加到DelayedTextBox就可以了:

public static readonly DependencyProperty DelayedTextChangedCommandProperty =
    DependencyProperty.Register(
        "DelayedTextChangedCommand",
        typeof(ICommand),
        typeof(DelayedTextBox),
        new PropertyMetadata(0));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM