命令绑定到中继命令不工作 [英] Command binding to relay command not working

查看:168
本文介绍了命令绑定到中继命令不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在C#中使用WPF开发一个简单的注册表。我有我的产品的按钮,如果他们按下(通过键盘快捷方式或鼠标按钮)产品订购。
我不知道我有多少产品(将从数据库加载)所以一个固定的解决方案不是我想要的。
我已经设法通过绑定到对象的列表框显示这些按钮。

I'm trying to develop a simple register in C# with WPF. I have buttons for my products and if they are pressed (via Keyboard shortcut or mouse button) the product is ordered. I don't know how much products I have (will be loaded from the database) so a fixed solution is not what I want. I've managed to display those buttons via a Listbox bound to the objects.

<ListView.ItemTemplate>
    <DataTemplate>
        <UniformGrid>
            <Button Template="{DynamicResource ButtonBaseControlTemplate1}" Style="{StaticResource ButtonStyle1}" Command="{Binding OrderCommand}" CommandParameter="{Binding}">
                <Button.Background>
                    <ImageBrush ImageSource="{Binding PictureUrl}" />
                </Button.Background>
                <DockPanel>
                    <TextBlock Text="{Binding Name}" FontSize="30"  DockPanel.Dock="Top" HorizontalAlignment="Center" Margin="0, 25, 0, 0"/>
                    <TextBlock Text="{Binding Price}" FontSize="15" HorizontalAlignment="Left" Margin="5"/>
                    <TextBlock Text="{Binding Shortcut}" FontSize="15" HorizontalAlignment="Right" DockPanel.Dock="Bottom" VerticalAlignment="Bottom" Margin="5"/>
                </DockPanel>
            </Button>
        </UniformGrid>
    </DataTemplate>
</ListView.ItemTemplate>

绑定命令不起作用。如果我点击按钮,什么也没有发生。如果我使用 Clicked 事件,一切正常,但我需要绑定到按钮的对象作为参数。

Binding a Command does not work. If I click on the button, nothing happens. If I use the Clicked event, everything works fine, but I need the object which is bound to the button as parameter.

这是我的命令属性:

public RelayCommand OrderCommand
{
    get
    {
        return new RelayCommand((p) => MessageBox.Show("Test"), (p) => true);
    }
}

如果一切都按预期工作, MessageBox 显示测试。

If everything would work as intended, there should be a MessageBox displaying "Test".

感谢您提前的帮助。

谨慎,
Stefan

Regards, Stefan

推荐答案

您必须更新命令绑定才能找到它您的Window / Usercontrol数据文本

You will have to update your command binding to find it in your Window/Usercontrol datacontext

假设Command在Windows DataContext中

Assuming Command is in Windows DataContext

Command="{Binding DataContext.OrderCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

这篇关于命令绑定到中继命令不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆