Command binding to relay command not working

夙愿已清 提交于 2019-12-12 23:08:34

问题


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>

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.

Here's my command property:

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

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

Thanks for your help in advance.

Regards, Stefan


回答1:


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

Assuming Command is in Windows DataContext

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



回答2:


You have to change the datacontext of your button. As it is now, the datacontext is the object in the listview. What you want is to use the datacontext of your listview.

Something like that

Datacontext="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}"


来源:https://stackoverflow.com/questions/19045771/command-binding-to-relay-command-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!