动态生成的按钮似乎不会触发它们的命令
本文关键字:命令 按钮 动态 | 更新日期: 2023-09-27 18:11:21
我有一个在运行时动态填充的ListBox。它有一个RequirementPreview
的DataType
,它需要将某些属性绑定到触发器、源和参数。但是,有一个命令绑定需要触发在数据上下文中设置的命令,但与模板数据类型无关。
我想要的是Button
触发'RevertDelete'命令并发送按钮所属的RequirementPreview
的Guid
。到目前为止,我按下按钮什么也没发生。
Xaml:
<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>
Xaml.cs:
[Dependency]
public IMainViewModel ViewModel
{
get { return this.DataContext as IMainViewModel; }
set { this.DataContext = value; }
}
编辑:
Command="{Binding RelativeSource={x:Static RelativeSource.PreviousData}, Path=RevertDelete}"
Command="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=RevertDelete}"
Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=RevertDelete}
我猜RevertDelete
命令不是RequirementPreview
类型的一部分,它作为模板的数据上下文。您需要为这个命令使用相对源绑定:
<Button Command="{Binding DataContext.RevertDelete, RelativeSource={RelativeSource AncestorType=ListBox}}"
CommandParameter="{Binding Guid}" />