【问题标题】:Binding a WPF Button CommandParameter to the Button itself in DataTemplate将 WPF 按钮 CommandParameter 绑定到 DataTemplate 中的按钮本身
【发布时间】:2012-09-06 23:55:31
【问题描述】:

我有一个代表 AppBar 按钮的 DataTemplate,我通过一组自定义 AppBarCommand 对象声明。

  public AppBarCommand(RelayCommand command, string buttonstyle)
  {
     Command = command;
     ButtonStyle = buttonstyle;
  }

<DataTemplate>
   <Button Command="{Binding Command}"
           Style="{Binding ButtonStyle, Converter={StaticResource StringNameToStyleConverter}}"/>
</DataTemplate>

我想添加一个 CommandParameter 绑定,但参数必须是 Button 本身。这样我就可以设置 Callisto 浮出控件的 PlacementTarget。这可能吗?

【问题讨论】:

  • 可能更容易处理 Button 的 Click 事件。您在处理程序中收到的第一个参数将是 Button。

标签: c# wpf binding datatemplate commandparameter


【解决方案1】:
<Button Command="{Binding Command}" 
        CommandParameter="{Binding RelativeSource={RelativeSource Self}}" />

您的 Command 属性应该是 RelayCommand 的通用版本:例如 RelayCommand&lt;object&gt;

【讨论】:

    【解决方案2】:

    像 Miklós Balogh 所说的那样回答,或者你可以:

    <Button x:Name="MyButton" Command="{Binding Command}" CommandParameter={Binding ElementName=MyButton ... /> 
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,但我在不同的环境中使用它:

      <MenuItem ItemsSource="{Binding MyList}">
          <MenuItem.ItemContainerStyle>
              <Style TargetType="{x:Type MenuItem}">
                  <Setter Property="Command" Value="{Binding RelativeSource={ RelativeSource FindAncestor, AncestorType={ x:Type Window}}, Path= DataContext.MyListItemCommand}"/>
                  <Setter Property="CommandParameter" Value="{Binding}" />
              </Style>
          </MenuItem.ItemContainerStyle>
      </MenuItem>
      

      所以我假设即使你这样写

      <Button Command="{Binding Command}" CommandParameter="{Binding}" />
      

      它应该可以工作。

      我还建议阅读this post 以更好地理解它。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-07-30
        • 2012-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多