动态生成的按钮似乎没有激活他们的命令?

时间:2016-10-04 10:21:27

标签: c# wpf xaml mvvm binding

我有一个在运行时动态填充的ListBox。它具有DataType RequirementPreview,需要将某些属性绑定到触发器,源和参数。但是,有一个命令绑定需要触发在datacontext中设置但与模板数据类型无关的命令。

我想要的是Button触发' RevertDelete' - 命令并发送按钮所属的Guid的{​​{1}}。截至目前,按下按钮时没有任何反应。

的Xaml:

RequirementPreview

Xaml.cs:

<ListBox Grid.Row="1" Grid.ColumnSpan="3" Margin="5" IsEnabled="{Binding IsEnabled}" ItemsSource="{Binding Requirements}" SelectionMode="Extended">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="SelectionChanged">
          <cmd:EventToCommand Command="{Binding SelectionChanged}"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
   <ListBox.ItemContainerStyle>
      <Style TargetType="ListBoxItem">
         <Style.Triggers>
            <DataTrigger Binding="{Binding IsDeleted}" Value="True">
                <Setter Property="Foreground" Value="red"/>
            </DataTrigger>
         </Style.Triggers>
         <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
         <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
      </Style>
   </ListBox.ItemContainerStyle>
      <ListBox.ItemTemplate>
         <DataTemplate DataType="{x:Type myModels:RequirementPreview}">
            <Grid>
               <Grid.ColumnDefinitions>
                 <ColumnDefinition Width="Auto"/>
                 <ColumnDefinition Width="45"/>
                 <ColumnDefinition Width="*"/>
               </Grid.ColumnDefinitions>

               <TextBlock Grid.Column="0" Text="{Binding Name}" ToolTip="{Binding Name}" HorizontalAlignment="Stretch"/>
               <Button Grid.Column="2" HorizontalAlignment="Right" IsEnabled="{Binding IsEnabled}" Visibility="{Binding IsDeleted, Converter={StaticResource BoolToVisibility}}" 
                                        Command="{Binding RevertDelete}" CommandParameter="{Binding Guid}" Height="10" Width="10"/>
            </Grid>
         </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

修改 尝试搞乱数据绑定;

    [Dependency]
    public IMainViewModel ViewModel
    {
        get { return this.DataContext as IMainViewModel; }
        set { this.DataContext = value; }
    }

两者都没有区别。

1 个答案:

答案 0 :(得分:1)

我猜RevertDelete命令不是RequirementPreview类型的一部分,它作为模板的数据上下文。您需要对此命令使用relative source绑定:

<Button Command="{Binding DataContext.RevertDelete, RelativeSource={RelativeSource AncestorType=ListBox}}" 
        CommandParameter="{Binding Guid}" />