Home > Software engineering >  How to use alternationindex on code behind wpf
How to use alternationindex on code behind wpf

Time:07-16

I have Itemcontrol in WPF. And Items source using Binding property.Items are only one button How can I show index of item when I clicked Button? I read about AlternationIndex but only show on the xaml page.

CodePudding user response:

You can pass it via Tag property.

    <ItemsControl AlternationCount="10">
    <ItemsControl.Items>
        <Button Tag="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource Mode=Self}}" Click="Button_Click"/>
        <Button Tag="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource Mode=Self}}" Click="Button_Click"/>
        <Button Tag="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource Mode=Self}}" Click="Button_Click"/>
        <Button Tag="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource Mode=Self}}" Click="Button_Click"/>
        <Button Tag="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource Mode=Self}}" Click="Button_Click"/>
    </ItemsControl.Items>
</ItemsControl>

Then you can parse it in Click handler.

//UserControl.xaml.cs
public void Button_Click(object sender, EventArgs args)
{
    var button = sender as Button;
    var alternationIndex = (int)Button.Tag;
}
  • Related