How can I find out which cell UniformGrid clicked on?

 <UniformGrid Rows="3" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"> <Label Background="Red"></Label> <Label Background="Green"></Label> <Label Background="Blue"></Label> </UniformGrid> 
  • Is it an option to handle click on the label? - Monk
  • @Monk, not an option. - Lightness
  • @Lightness: Why? - VladD

1 answer 1

There is no easy and fast way. It is possible only for O (n).

 private void UniformGrid_MouseDown(object sender, MouseButtonEventArgs e) { // ΡƒΠ·Π½Π°Π΅ΠΌ, Π½Π° ΠΊΠ°ΠΊΠΎΠΌ элСмСнтС ΠΊΠ»ΠΈΠΊΠ½ΡƒΠ»ΠΈ var element = e.Source as UIElement; if (element != null) { // ΡƒΠ·Π½Π°Π΅ΠΌ индСкс этого элСмСнта срСди всСх ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ»ΠΎΠ² Π³Ρ€ΠΈΠ΄Π° int index = UniformGrid.Children.IndexOf(element); // ΡƒΠ·Π½Π°Π΅ΠΌ ряд ΠΈ ΠΊΠΎΠ»ΠΎΠ½ΠΊΡƒ int row = index / UniformGrid.Columns; int column = index % UniformGrid.Columns; } } 

It is possible that it would be better to follow the MVVM path, where the content will be filled through the binding and where the cell number you will control yourself.

  • 2
    Since in our case n == 3 (and based on the problem, it is reasonable to assume that N <1000), then O (1). If you really need to quickly display the item in the index, you can hang the index once in the Tag. - VladD
  • @VladD is reasonable. - andreycha
  • @andreycha, thanks, that's exactly what I need. - Lightness
  • one
    @Lightness is nothing! - andreycha