【问题标题】:Bind a value to a control's absolute position in XAML将值绑定到 XAML 中控件的绝对位置
【发布时间】:2009-12-14 14:52:54
【问题描述】:

有没有办法使用 XAML 将值绑定到控件的绝对位置?

我有一个Line 元素,我想在我的应用程序中的两个Buttons 之间绘制它。我在想将Line 的起点绑定到Button 的位置将是实现这一目标的最简单方法,以某种方式使用RelativeSource

【问题讨论】:

    标签: wpf xaml binding wpf-positioning


    【解决方案1】:

    看来你想要这样的东西:

    <UserControl x:Class="PracticeSample.MyButton"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <Button x:Name="button" Content="Add" HorizontalAlignment="Center" VerticalAlignment="Top"/>
        <Line Stroke="Black" X1="0" Y1="0" HorizontalAlignment="Center" X2="{Binding ElementName=button, Path=ActualWidth}" Y2="{Binding ElementName=button, Path=ActualHeight}"/>
    </Grid>
    

    在您的页面中使用此 MyButton 代替 Button,

    编辑: 如果你想在两个控件之间画线 不要使用上面的代码示例,而是直接在您的页面中尝试:

    <Canvas HorizontalAlignment="Left" Margin="10">
        <Button x:Name="button2" Content="Add" Canvas.Left="10" Canvas.Top="5"/>
        <Button Name="button" Content="Refresh Control" Canvas.Left="100" Canvas.Top="50"/>
        <Line Stroke="Black" X1="{Binding Path=(Canvas.Left),ElementName=button2}" Y1="{Binding Path=(Canvas.Top), ElementName=button2}" X2="{Binding (Canvas.Left), ElementName=button}" Y2="{Binding (Canvas.Top), ElementName=button}"/>
    </Canvas>
    

    希望这会有所帮助!

    【讨论】:

    • 我最终在我的代码隐藏文件中进行了绘图,以便我可以对位置进行一些计算,而不仅仅是元素的角落。
    【解决方案2】:

    定义一个带有 Button 和 Line 的模板,放置在您喜欢的任何位置,然后在 Button 的位置使用此模板。

    【讨论】:

    • 对不起,我没有指定——我不能使用模板,因为我想同时绑定起点和终点。我想在两个任意元素之间画一条线。
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多