【问题标题】:How to Set listbox location in WPF [duplicate]如何在 WPF 中设置列​​表框位置 [重复]
【发布时间】:2014-02-23 04:24:06
【问题描述】:

我想设置列表框位置。在 Winform 中,我使用此代码 listbox.Location 做到了这一点,但在 WPF 中没有 listbox.Location 属性。

编辑 1:

 var rect = txtBox.GetRectFromCharacterIndex(txtBox.CaretIndex);

 var point = rect.BottomRight;

 lstBox1.Visibility = Visibility.Visible;

 //Want to achieved this
 //TextBox.Location = point;

我正在用列表框创建类似 Intellisense 的东西

【问题讨论】:

  • 请添加您的代码,而不是位置,尝试使用 Margin 属性
  • 你不能使用winforms相同的原理。
  • 我想在列表框的 Y 轴上输入点值。
  • 请看我下面的帖子——边距有四个部分:左、上、右、下。你可以喂那个。左为 X,上为 Y。

标签: c# wpf wpf-controls


【解决方案1】:

这完全取决于父面板是什么来确定如何设置列表框的位置。您需要阅读更多关于 WPF 中的Layouts 的信息。让我们看看 2 个面板来帮助您入门,Grid 和 Canvas。

<Grid>
  <ListBox x:Name="lb" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>

lb.Margin = new Thickness(10,10,0,0);

上面的示例将 Grid 中的 ListBox lb 设置在位置 (10,10)。

<Canvas>
  <ListBox x:Name="lb"/>
</Canvas>

Canvas.SetTop(lb, 10);
Canvas.SetLeft(lb, 10);

上面的例子对 Canvas 中的 lb 做同样的事情。

如您所见,这取决于您将列表框放入哪种类型的面板才能正确设置位置。

【讨论】:

    【解决方案2】:

    ListBox 的位置是相对于它所在的控件确定的。要在它的父控件中设置位置,您可以使用 Horizo​​ntalAlignment、VerticalAlignment 和 Margin 属性。

    这是一个例子:

    <Window x:Class="WpfApplication14.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
        <Grid>
             <ListBox HorizontalAlignment="Left" Height="100" Margin="197,105,0,0" VerticalAlignment="Top" Width="100"/>
         </Grid>
    </Window>
    

    注意 - 所有这些属性也可以通过编程方式使用。

    谢谢,

    埃里克

    【讨论】:

    • 我在文本框 GotFocus 事件上使用了这个 var rect = txtBox.GetRectFromCharacterIndex(txtBox.CaretIndex); var point = rect.BottomRight; lstBox1.Margin = new Thickness(0, point.Y, 0, 0); 但问题是当文本框聚焦时,列表框刚刚停靠到主窗口
    【解决方案3】:

    您可能应该阅读 WPF 布局,但是您可以使用 ListBox.MarginListBox 定位在硬编码位置。

    listbox.Margin = new Thickness( 25, 200, 0, 0 );
    

    或在 XAML 中

    <ListBox Margin="25,200,0,0"/>
    

    【讨论】:

    • 我想在列表框的 y 轴上设置点值。在 WinForm 中我确实喜欢这个 listbox.Location = p 其中 p 是 p.Y += (int)rtbInput.Font.GetHeight()*2;
    • WPF 不能以这种方式工作。它希望您创建一个结构化的布局。当您创建这样的布局时,窗口大小调整和其他此类功能几乎可以为您处理。Consider this simple tutorial.
    猜你喜欢
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 2012-05-24
    相关资源
    最近更新 更多