【问题标题】:Command binding to relay command not working命令绑定到中继命令不起作用
【发布时间】:2013-10-03 10:57:20
【问题描述】:

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

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

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

这是我的命令属性:

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

如果一切都按预期工作,应该有一个 MessageBox 显示“测试”。

提前感谢您的帮助。

问候, 斯蒂芬

【问题讨论】:

  • 该命令是否与例如在同一视图模型中绑定的名字?
  • OrderCommand 在哪里定义?你在哪里指定DataContext?您还可以在每次获取时创建 OrderCommand 的新实例
  • OrderCommandMainWindowViewModel 中定义,该视图设置为DataContext
  • 所以OrderCommand 定义在与PictureUrlNamePriceShortcut 相同的类中,这些字段显示正常吗?
  • No PictureUrl, Name, ... 是我班级 Product 的属性。在我的MainWindowViewModel 中是一个ObservableCollection&lt;Product&gt;,它存储所有这些对象。在我的View 中,我在ListView 中显示这些对象,而不是显示文本或某事。类似的 I 显示按钮。这些按钮现在需要一个RelayCommand,在我的例子中是OrderCommand,以及ListView 中的按钮/对象作为参数。

标签: c# wpf mvvm command


【解决方案1】:

您必须更新您的命令绑定才能在您的窗口/用户控件数据上下文中找到它

假设 Command 在 Windows DataContext 中

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

【讨论】:

    【解决方案2】:

    您必须更改按钮的数据上下文。就像现在一样,数据上下文是列表视图中的对象。您想要的是使用列表视图的数据上下文。

    类似的东西

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

    【讨论】:

    • 执行Command 有效,但我不想更改DataContext,因为现在我所有的显示成员都消失了(比如价格、名称……),而我不想'如果我执行Command,则无法获取正确的对象作为参数。
    • 你是对的。我没有注意到按钮的许多属性都绑定到列表中对象的属性。但现在你有想法了
    • 对不起,我现在不知道....用你的解决方案我可以执行命令,但是我没有得到正确的参数类型(类型是@ 987654325@ 而不是 Product) 并且我的显示属性不显示...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 2020-03-06
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多