Silverlight 4 MVVM : Unable to Databind ICommand

标签 silverlight data-binding mvvm silverlight-4.0

我创建了一个 Silverlight 用户控件。标记是:

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

后面的代码将依赖属性“OKCommand”声明为:
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)
{      
}

现在我想在另一个页面上使用用户控件,其中 View 和 ViewModel 定义了我希望 OKCommand 绑定(bind)到的命令。 XAML 标记如下:
<local:TestControl OKCommand="{Binding Path=TestControlOk}"/>

但是,当我单击按钮时,它不会执行任何操作。关于我在这里做错了什么的任何线索。

最佳答案

您需要显示包含 TestControlOk 属性的 View 模型,以便我们判断这是否是问题的一部分。

UserControls 不会自动将自己注册为数据上下文,因此用户控件内的绑定(bind)不会有任何要绑定(bind)的内容。你有

this.DataContext = this;

UserControl 代码隐藏中的任何位置以使您的第一个绑定(bind)能够实际工作?

或者,您可以执行以下操作:
<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>

注意 ElementName=指向 XAML 中根 UserControl 元素的绑定(bind)的一部分。

关于Silverlight 4 MVVM : Unable to Databind ICommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3788950/

相关文章:

javascript - 消除 Internet Explorer 中 Thread.Sleep 上的死锁?

silverlight - silverlight中是否可以动态更改所需的数据注释

.net - Silverlight 和普通 .NET Framework 之间的 CLR 差异?

java - 如何在 Controller 中实现正确的数据绑定(bind)?

rest - JsonMappingException : Already had POJO for id

c# - 在 DynamicResource ResourceKey 中绑定(bind) wpf mvvm

WPF:Unity:关闭后重用窗口

silverlight - MVVM Light Nuget包中缺少SimpleIoc

c# - 将事件绑定(bind)到方法,为什么在UWP中有效?

c# - 隐藏 ListView ,直到按下按钮