开发者

Silverlight 4 MVVM: Unable to Databind ICommand

开发者 https://www.devze.com 2023-01-17 06:19 出处:网络
I have created a Silverlight User Control. The markup is: <StackPanel Grid.Row=\"4\" Grid.Column=\"0\" Orientation=\"Horizontal\" Width=\"Auto\" Margin=\"5\">

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
    = Depende开发者_StackOverflow社区ncyProperty.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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号