views:

39

answers:

1

I have created a Silverlight User Control. The markup is:

<StackPanel Grid.Row="4" Grid.Column="0" Orientation="Horizontal" Width="Auto" Margin="5">
    <Button Content="OK" Margin="0,0,5,5" MinWidth="50" Command="{Binding OKCommand}"  />
</StackPanel>

The code behind declares a Dependency property 'OKCommand' as:

public ICommand OKCommand
{
    get
    {
        return (ICommand)GetValue(OKCommandProperty);
    }
    set
    {
        SetValue(OKCommandProperty, value);
    }
}

public static readonly DependencyProperty OKCommandProperty
    = DependencyProperty.Register("OKCommand", typeof(ICommand), typeof(TestUserControl), new PropertyMetadata(null, OKCommandProperty_PropertyChangedCallback));

private static void  OKCommandProperty_PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{      
}

Now I want to use the user control on another page where which is the View & the ViewModel defines the command to which I want the OKCommand to be bound. The XAML markup is as such:

<local:TestControl OKCommand="{Binding Path=TestControlOk}"/>

However when I click the button it does not execute anything. Any clues as to what I am doing wrong here.

A: 

You need to show the view model that contains the TestControlOk property so we can tell if that's part of the problem.


UserControls do not register themselves as the data context automatically so the binding inside the user control won't have anything to bind to. Do you have

this.DataContext = this;

anywhere in the UserControl codebehind to enable your first binding to actually work?

Alternatively, you can do something like so:

<UserControl .....
    x:Name="MyUserControl">
    <StackPanel Grid.Row="4" Grid.Column="0" Orientation="Horizontal" Width="Auto" Margin="5">
        <Button Content="OK" Margin="0,0,5,5" MinWidth="50" 
            Command="{Binding OKCommand, ElementName=MyUserControl}"  />
    </StackPanel>
</UserControl>

Note the ElementName= part of the binding pointing to the root UserControl element in your XAML.

Adam Sills