简体   繁体   中英

Own property of UserControl in WPF

I have a user control with 2 grids on it. Now I want to be able to retrieve the grid that has the focus and expose it to my view model. How can I do this in WPF? I want to fill a property in my view model with the name of the Grid that has focus. It seems not to be easy.

Can anyone help?

Thx!

You really should reconsider your design if you are exposing UI elements or specific parts to your viewmodel. Usually your viewmodel should not know of any specific ui element. What exactly do you want to do with the name of the ui element? You could listen to a GotFocus event on your two grids like

<Grid x:Name="Grid1" GotFocus="OnGridGotFocus"/>
<Grid x:Name="Grid2" GotFocus="OnGridGotFocus"/>

and add this method to your UserControl, in this method you could retrieve it via

private static void OnGridGotFocus(object aSender, RoutedEventArgs aE)
{
   string name = (string)(aSender as DependencyObject).GetValue(NameProperty);
}

the name could now be written into a DependencyProperty which you bind to your view model. But again, i still think you should not do this.

If you explain what exactly you are trying to achieve, maybe we can help you better.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM