2

我在 Silverlight 3 和 Prism 中有一个简单的测试应用程序,我只是想将一个按钮单击绑定到我在视图模型上创建的一个简单命令。这是一个测试应用程序,只是为了让指挥工作。当我运行它时,我收到一个绑定错误,告诉我视图找不到命令:

System.Windows.Data 错误:BindingExpression 路径错误:在“Bind1.ShellViewModel”“Bind1.ShellViewModel”上找不到“MyCommand”属性(HashCode=8628710)。BindingExpression: Path='MyCommand' DataItem='Bind1.ShellViewModel' (HashCode=8628710); 目标元素是'System.Windows.Controls.Button'(名称='');目标属性是'Command'(类型'System.Windows.Input.ICommand')..

这是我的外壳视图:

<UserControl 
x:Class="Bind1.ShellView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:Commands="clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation" 
Width="400" Height="300">
<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel>
        <TextBlock Text="Hello World!"></TextBlock>
        <Button Content="{Binding ButtonLabel}" Commands:Click.Command="{Binding Path=MyCommand}" />
    </StackPanel>
</Grid>
</UserControl>

在视图的构造函数中,我实例化了一个 ViewModel(我还不担心使用容器......):

public partial class ShellView : UserControl
{
    public ShellView()
    {
        InitializeComponent();
        DataContext = new ShellViewModel();
    }
}

这是我的视图模型:

public class ShellViewModel
{
    public string ButtonLabel { get { return "DoIt!!"; } }
    public DelegateCommand<object> MyCommand = new DelegateCommand<object>(ExecuteMyCommand);
    public static void ExecuteMyCommand(object obj)
    {
        Debug.WriteLine("Doit executed");
    }
}

按钮标签绑定工作正常,因此视图找到 ViewModel OK。

为什么找不到 MyCommand?这让我发疯 - 我显然在做一些非常错误的简单事情......

非常感谢。

4

1 回答 1

2

What an idiot... Sorry for wasting your time.

I forgot to make MyCommand a property!!! Too much staring at the screen. It was just a public field so the binding infrastructure couldn't see it. All is well now.

于 2010-02-24T16:27:09.050 回答