绑定

时间:2016-07-19 14:37:35

标签: c# wpf xaml button datatemplate

我正在使用Wpf而我正在将List<Value>传递给xaml中的<ItemsControl>。我想将string对象中的Value绑定到Button的命令。这个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");
    }

除此之外的所有内容都正常工作,并且绑定时使用相同的Object。 我做错了什么?

2 个答案:

答案 0 :(得分: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}" />

答案 1 :(得分:1)

Button.Command属性仅绑定到实现ICommand接口的对象。 如果要调用其名称为ButtonClickMethod的方法,则必须:

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