【问题标题】:DataTemplate button command from binding来自绑定的 DataTemplate 按钮命令
【发布时间】:2016-11-22 12:41:06
【问题描述】:

我正在使用 Wpf,并且在 xaml 中将 List<Value> 传递给 <ItemsControl>。我想将Value 对象中的string 绑定到按钮的命令。此 xaml 部分如下所示:

    <Grid Margin="0,0,2,0">
    <Grid Margin="10">
        <ItemsControl Name="details">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Grid Margin="0,0,0,5">
                        <Grid.ColumnDefinitions>
                            ....
                        </Grid.ColumnDefinitions>
                        ...
                        <Button Grid.Column="2"
                                Content="{Binding ButtonContent}"
                                Visibility="{Binding ButtonVisibility}"
                                Command="{Binding ButtonClickMethod}" />
        ...

我的Value 班级如下所示:

public class Value
{        
    ...
    public string ButtonClickMethod { get; set; }

}

我正在设置字符串链接:

v.ButtonClickMethod = "RelatedActivityId_OnClick";

并且Method在同一个类中,看起来像这样:

private void RelatedActivityId_OnClick(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("RelatedActivityId_OnClick");
    }

除此之外的一切都正常工作,并取消绑定相同的对象。 我做错了什么?

【问题讨论】:

  • 那么字符串ButtonClickMethod包含要执行的方法的名称?
  • 是的,我刚刚添加了更多代码

标签: c# wpf xaml button datatemplate


【解决方案1】:

Button 的 Command 属性是 ICommand 类型,因此您不能将其绑定到 string 值。

您需要将您的ButtonClickMethod 更新为ICommand 类型或创建一个新属性以将您绑定到Command

有关 ICommand 的示例实现,请参阅 this 答案。

如果您需要按钮根据参数(字符串值?)执行代码,那么您可以使用CommandParameter 属性,然后在您的命令处理程序中使用该参数。

public class Value
{        
    public Value()
    {
        ButtonCommand  = new RelayCommand((a) => true, CommandMethod); 
    }

    public RelayCommand ButtonCommand {get; set; }
    public string ButtonClickMethod { get; set; }

    private void CommandMethod(object obj)
    {
        MessageBox.Show(obj?.ToString());
    }
}

和 XAML:

<Button Grid.Column="2"
         Content="{Binding ButtonContent}"
         Visibility="{Binding ButtonVisibility}"
         Command="{Binding ButtonCommand}"
         CommandParameter="{Binding ButtonClickMethod}" />

【讨论】:

  • (如果目标是基于动态设置的值执行,那么分配不同的命令比使用字符串和反射要容易得多。)
  • 我希望他可以使用参数来决定调用哪个方法,而不是通过反射找到它...假设他可以调用的方法数量有限。
【解决方案2】:

Button.Command 属性仅绑定到实现 ICommand 接口的对象。 如果你想调用一个名为 ButtonClickMethod 的方法,你必须:

  1. 创建一个实现 ICommand 接口的类。
  2. 创建该类的对象并将其绑定到您的按钮(将其绑定到 Button.Command)。
  3. 将 Value.ButtonClickMethod 作为 CommandParameter 传递给 ICommand 对象。
  4. 使用它来调用您想要的任何方法。

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2018-07-31
    • 2017-01-31
    • 2012-09-03
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-05-11
    相关资源
    最近更新 更多