【问题标题】:Deleting element from ItemsControl by pressing button XAML C++/CX通过按下按钮 XAML C++/CX 从 ItemsControl 中删除元素
【发布时间】:2025-12-10 17:55:02
【问题描述】:

我试图在不使用 Window.CommandBinding 的情况下从以下 ItemsControl 中删除一个元素。有没有更简单的方法来做到这一点?

XAML:

        <ItemsControl ItemsSource="{Binding Path=MyStringArray}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Button Content="Abcd"/>
                        <Button Content="-" Click="Button_Click_1"/>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

如果没有更简单的方法,如何使用 Window.CommandBindings 来完成

另外,在这段代码中,如何让第一个按钮的宽度等于屏幕的整个宽度减去第二个按钮的宽度?

【问题讨论】:

    标签: xaml windows-8 microsoft-metro itemscontrol c++-cx


    【解决方案1】:

    使用项目模板上的按钮删除项目控件中的项目的最简单方法是使用命令绑定,命令参数绑定到当前项目。然后从支持集合中删除当前项目。

    要实现所需的按钮间距,请使用网格进行布局。创建两个GridColumns。第一个宽度为*,第二个宽度为Auto。假设您正确设置了 ItemsControl 的间距,这将实现您所寻找的间距。

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
    
        <Button Grid.Column="0" Content="Abcd"/>
        <Button Grid.Column="1" Content="-" Command="{Binding YourCommand}" CommandParamter={Binding}/>
    </Grid>
    

    有关更完整的命令绑定示例,请参阅here,有关命令绑定的便利类,请参阅here

    【讨论】:

    • 谢谢。我不太了解CommandBinding。我确实找到了另一种方法。我在按钮单击方法中使用以下代码行: myString = static_cast<:ui::xaml::controls::button>(sender)->DataContext->ToString();它为我提供了向量中字符串的对应值,因此我可以进行搜索和删除元素(我没有重复项)。我真的不明白 DataContext 返回什么。我假设它给出了具有绑定的第一个父级的绑定值
    • 这也差不多。发件人是Button,因此按钮的DataContextButton 的上下文相同。从您上面的内容来看,&lt;ItemsControl ItemsSource="{Binding Path=MyStringArray}"&gt;,此绑定正在查看 ItemsControlDataContext,然后在其中查找 MyStringArray