XAML - 获取相对于整个窗口的用户控件位置作为绑定属性 [英] XAML - get user control position relative to whole window as binding property

查看:29
本文介绍了XAML - 获取相对于整个窗口的用户控件位置作为绑定属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 XAML 的新手,所以请注意我的问题可能包含一些主题误解.

I'm new to XAML, so please be aware my question may contain some topic misundrestanding.

是否可以绑定 XAML 用户控件全局(相对于窗口)位置以检查它当前是否在屏幕上可见?用户控件插入到 ScrollViewer 中,我认为是这样的:

Is it posible to bind XAML usercontrol global (relative to window) position to check if it's currently visible on screen? Usercontrol is inserted inside ScrollViewer and I think on something like:

  <UserControl x:Class="Test.MessageControl"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Width="300">
      <StackPanel >
          <Label Name="LabelTest" 
          Content="{Binding RelativeSource={RelativeSource Self}, 
          Path=MAGIC-GOES-HERE-Location.Y }" />
      </StackPanel>
   </UserControl>

推荐答案

不,不可能在 XAML 中获取控件的位置"(至少不像我们习惯的那样直接获取).在 WPF 中,控件不再具有位置"属性.控件和屏幕元素只有宽度和高度属性,这无法帮助您找到它们在窗口中的位置.

No, it is not possible to get the "location" of your controls in XAML (not directly like we are used to, at least). In WPF, controls don't have "location" properties anymore. Controls and screen elements only have width and height properties, which won't help you find where they are in the window.

但是:如果您真的需要知道某物在哪里,您可以使用属性找出它的父控件.(微软已经做到了,因此这是唯一可靠的方法.)

BUT: If you really need to know where something is, you CAN figure it out using properties of the parent control. (Microsoft has made it so that this is the only reliable way to do this anymore.)

示例:
如果您有一个包含两行的网格,并且您的 UserControl 位于第二行 - 您可以将第一行的 ActualHeight 属性视为 UserControl 的Location.Y"属性,而不是查看控件本身为您提供它的位置.

Example:
If you have a grid with two rows, and your UserControl is in the second row - you can treat the ActualHeight property of the first row like it is the "Location.Y" property of your UserControl, instead of looking to the control itself to provide you with its location.

这是您必须习惯的事情,因为不再有任何方法可以绕过它.

This is something that you will have to get used to, since there is no longer any way to get around it.

考虑在设计中的某处使用 <Grid> 元素.它以非常直接的方式提供有关控件位置的信息.它的工作方式类似于动态调整大小的 HTML 表格的智能版本.您可以检索任何行或列的 ActualWidth 和 ActualHeight 属性 - 如果需要,甚至可以检索整个网格本身.

Consider using the <Grid> element somewhere in your design. It provides information about the location of your controls in a very straight-forward kind of way. It works like a smarter version of a dynamicly-sizing HTML table. You can retrive ActualWidth and ActualHeight properties of any row or column - or even of the entire grid itself if you want.

这篇关于XAML - 获取相对于整个窗口的用户控件位置作为绑定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆