Search code examples
xamlwindows-8microsoft-metroitemscontrolc++-cx

Deleting element from ItemsControl by pressing button XAML C++/CX


I am trying to delete an element from the following ItemsControl without using Window.CommandBinding. Is there an easier way to do this?

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>

If there is not an easier way, how can it be done with Window.CommandBindings

Also, in this code, how can I make the width of the first button take the entire width of the screen minus the width of the second button?


Solution

  • The easiest way to remove an item in an itemscontrol using a button on the item template is using a command binding with the command parameter bound to the current item. You then remove the current item from the backing collection.

    To achieve the button spacing you're looking for, use a grid for layout. Create two GridColumns. Give the first one a width of * and the second one a width of Auto. Assuming you have the spacing for your ItemsControl set correctly, this will achieve the spacing your looking for.

    <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>
    

    See here for a more complete commmand binding example and here for a convenience class for command binding.