Please tell me how to make a unique check, for example, that ellipse is a child of the Grid? ...

private void Window_PreviewMouseDown_2(object sender, MouseButtonEventArgs e) { if ((e.Source as Control).Parent is Grid == true){ // Ура, наш control или ellipse или usercontrol внутри grid'а } } 

Everything seems easy, but when in e.Source is not a standard System.Windows.Controls , but for example one of System.Windows.Shapes then the program crashes due to the type mismatch, and if there is a user control, then I’m generally afraid to imagine what will happen there :)

  • Strange, usually you don’t want to know which object your object is in. What is the real problem you are solving? - VladD
  • really strange. Between the ellipse and the grid there may be other positioning containers, for example StackPanel. On the other hand, among the parent containers of any control on the form, you can always find a grid, and not even one))), That is, closer to the algorithms - you need to look not for the immediate ancestor, but in the loop - higher and higher, until we find. And on the other hand, we will always find a grid, because they are everywhere - ale

1 answer 1

The check should be:

 (ellipse.Parent != null) && (ellipse.Parent is Grid) 

(By the way, the ellipse does not have the Source property, so it’s not clear how you compile it.)


For your case, just rolls

 var fe = (FrameworkElement)(e.Source); if ((fe.Parent != null) && (fe.Parent is Grid)) { ... 

Update: As @Igor suggests, for the case of fe.Parent == null check fe.Parent is Grid will return false , so the first check is not needed. Total:

 var fe = (FrameworkElement)(e.Source); if (fe.Parent is Grid) { ... 
  • No, but it won't work if there is a button instead of ellipse, I did it already. - alex-rudenkiy
  • @ alex-rudenkiy: (1) The question actually asks about Ellipse , but (2) This code should work and if the type of the ellipse variable is Button . - VladD
  • I just wanted to find out if there is any unique type that could be done with ((e.Source as SUPERTYPE).Parent is Grid == true) and it would all work with custom controls and standard ones (System.Windows. Controls) and non-standard (System.Windows.Shapes) - alex-rudenkiy
  • @ alex-rudenkiy: Not-not, if you write as , the result may be null . - VladD
  • one
    @VladD - (fe.Parent != null) not needed - Igor