【问题标题】:Get PropertyGrid TextBox获取 PropertyGrid 文本框
【发布时间】:2013-07-19 16:21:24
【问题描述】:

如何从指定字段中获取 PropertyGrid 的 TextBox? 我需要这个 TextBox 来设置指向文本结尾的指针。

var num = txtBox.GetCharIndexFromPosition(Cursor.Position);
txtBox.SelectionStart = num + 1;
txtBox.SelectionLength = 0;

那么我怎样才能从 PropertyGrid 中得到这个 TextBox 呢? 此外,PropertyGrid 中的属性是只读的。

【问题讨论】:

  • 您需要在文本框中选择文本吗?

标签: c# winforms textbox propertygrid


【解决方案1】:

如果您希望光标位于文本框中写入的最后一个字符之后,您可以依赖以下代码(由TextBoxTextChanged Event 触发):

private void txtBox_TextChanged(object sender, EventArgs e)
{
    int newX = txtBox.Location.X + TextRenderer.MeasureText(txtBox.Text, txtBox.Font).Width;
    int newY = txtBox.Bottom - txtBox.Height / 2;
    if (newX > txtBox.Location.X + txtBox.Width)
    {
        newX = txtBox.Location.X + txtBox.Width;
    }
    Cursor.Position = this.PointToScreen(new Point(newX, newY));
}

请记住,它的 Y 位置始终在中间。

-----王者评论后更新

至于问题中的代码提到了TextBox,我的答案集中在TextBox。尽管如此,KingKing 是对的,PropertyGrid 必须考虑在内。在这些行下面,我修改了您可以在MSDN 中找到的代码,用于PropertyGrid

private void Form1_Load(object sender, EventArgs e)
{
    PropertyGrid propertyGrid1 = new PropertyGrid();
    propertyGrid1.CommandsVisibleIfAvailable = true;
    propertyGrid1.Location = new Point(10, 20);
    propertyGrid1.Size = new System.Drawing.Size(400, 300);
    propertyGrid1.TabIndex = 1;
    propertyGrid1.Text = "Property Grid";

    this.Controls.Add(propertyGrid1);

    propertyGrid1.SelectedObject = txtBox;
}

txtBox 添加到propertyGrid1 后,其位置被更新,因此可以毫无问题地使用原始代码。

综上所述,思路不是在PropertyGrid内部寻找TextBox,而是直接访问TextBox控件(在运行时添加到PropertyGrid)。

【讨论】:

  • OP 如何访问txtBox?他想访问与PropertyGrid 中的字段相对应的特定文本框。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多