WPF中UserControl自己的属性

发布于 2024-12-03 12:27:30 字数 138 浏览 0 评论 0原文

我有一个带有 2 个网格的用户控件。现在我希望能够检索具有焦点的网格并将其公开给我的视图模型。我怎样才能在 WPF 中做到这一点? 我想用具有焦点的 Grid 的名称填充视图模型中的属性。看来这并不容易。

有人可以帮忙吗?

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半枫 2024-12-10 12:27:30

如果您将 UI 元素或特定部分暴露给视图模型,您确实应该重新考虑您的设计。通常你的视图模型不应该知道任何特定的 ui 元素。您到底想用 ui 元素的名称做什么?您可以在两个网格上收听 GotFocus 事件
将此

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

方法添加到您的 UserControl 中,在此方法中您可以通过

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

名称检索它,现在可以将其写入绑定到视图模型的 DependencyProperty 中。但我还是认为你不应该这样做。

如果您解释一下您到底想要实现什么目标,也许我们可以更好地帮助您。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文