简体   繁体   中英

Can't bind to a command in my custom control

I created a control based of TextBox that looks like this:

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

I then create Foo.xaml with the following code:

<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:

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

When I run my project, I get the following error when Foo.xaml gets loaded:

WinRT information: Failed to assign to property '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'. [Line: 29 Position: 103] The text associated with this error code could not be found.

Failed to assign to property 'TestApp.Helpers.DelayedTextBox.DelayedTextChangedCommand'. [Line: 29 Position: 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.

Adding the following to DelayedTextBox did the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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