Command binding does not work when host control is added programmatically in wpf

This is strange. I have a UserControl (MyControl) with a button inside. I added a command to this buttonwhose target is another user control that is again added to the same window.

When I add UserControl statically to xaml in the CustomControl host space, the CommandBinding system works fine, where, like the same thing, it does not work if the UserControl is added programmatically (by the Loaded event of this window).

What could be the reason. Am I missing something here?!?

Update:

* The best representation of my words as images. I also downloaded my binary source code @ https://code.google.com/p/commandbindingsample/ and

http://cid-6fc1e241d4534589.office.live.com/embedicon.aspx/Wpf%20Samples/CommandBinding.zip (not supported by version) *

alt text

+3
source share
1 answer

In a user control, you set CommandBindingas follows:

CommandTarget="{Binding ElementName=userControl11}"

If you look in the Output window while your program is running, you will see the following:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=userControl11'. BindingExpression:(no path); DataItem=null; target element is 'Button' (Name=''); target property is 'CommandTarget' (type 'IInputElement')

, userControl11. . , XAML, , , XAML , , '. , , .

, . :

public IInputElement CommandTarget
{
    get { return (IInputElement)GetValue(CommandTargetProperty); }
    set { SetValue(CommandTargetProperty, value); }
}

public static readonly DependencyProperty CommandTargetProperty =
        DependencyProperty.Register("CommandTarget", typeof(IInputElement), typeof(UserControl1), new UIPropertyMetadata(null));

XAML :

<Button Content="Click" 
        Command="local:Commands.ClickCommand" 
        CommandTarget="{Binding RelativeSource={RelativeSource AncestorType=UserControl}, Path=CommandTarget}" />

, , . , UserControl1 , , . ( , , , " ", , , , .)

, .

+1

Source: https://habr.com/ru/post/1772070/


All Articles