简体   繁体   English

WPF中UserControl的自己的属性

[英]Own property of UserControl in WPF

I have a user control with 2 grids on it. 我有一个带有2个网格的用户控件。 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? 如何在WPF中执行此操作? I want to fill a property in my view model with the name of the Grid that has focus. 我想用具有焦点的Grid名称在视图模型中填充一个属性。 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. 如果要将UI元素或特定部分暴露给视图模型,则确实应该重新考虑设计。 Usually your viewmodel should not know of any specific ui element. 通常,您的视图模型不应该知道任何特定的ui元素。 What exactly do you want to do with the name of the ui element? 您到底想使用ui元素的名称做什么? You could listen to a GotFocus event on your two grids like 您可以在两个网格上听GotFocus事件,例如

<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 并将此方法添加到您的UserControl中,在此方法中,您可以通过

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. 该名称现在可以写入到您绑定到视图模型的DependencyProperty中。 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. 如果您确切说明您要实现的目标,也许我们可以为您提供更好的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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