gpt4 book ai didi

.net - 获取文本框中字符的坐标?

转载 作者:行者123 更新时间:2023-12-04 17:16:14 24 4
gpt4 key购买 nike

我想增强这个 WPF DateTimePicker control通过在所选字段的上方和下方添加一个装饰器,例如

DateTimePicker

为此,我需要计算出 TextBox 中所选内容开始和结束的 X 坐标。我该怎么做?

最佳答案

(编辑:Derp - 我错过了你的“只有选择”部分......这会给你全文长度)

您要查找的属性是 TextBox 上的 ExtentWidth:

(抱歉,手头只有 LINQPad,所以必须用困难的方式来做...)

var wnd = new Window();
var panel = new StackPanel();
wnd.Content = panel;

var textBox = new TextBox();
textBox.Name = "theTextBox";
textBox.FontFamily = new FontFamily("Arial");
textBox.FontSize = 20;
textBox.Text = "This is some text I want to measure";
panel.Children.Add(textBox);

wnd.Show();

var showWidth = new TextBlock();
showWidth.Text = "This should show the size of the text";
var binding = new System.Windows.Data.Binding();
binding.Path = new PropertyPath("ExtentWidth");
binding.Source = textBox;
binding.Mode = System.Windows.Data.BindingMode.OneWay;
showWidth.SetBinding(TextBlock.TextProperty, binding);
panel.Children.Add(showWidth);

编辑#2:好的,试试这个:(同样,只有 LINQPad)

void Main()
{
var wnd = new Window();
var panel = new StackPanel();
var textBox = new TextBox();
textBox.FontSize = 20;
textBox.Text = "This is some text I want to measure";
textBox.SelectionChanged += OnSelectionChanged;
showWidth = new TextBlock();
panel.Children.Add(textBox);
panel.Children.Add(showWidth);
wnd.Content = panel;
wnd.Show();
}

private TextBlock showWidth;

private void OnSelectionChanged(object sender, EventArgs args)
{
var tb = sender as TextBox;
double left = tb.GetRectFromCharacterIndex(tb.SelectionStart).Left;
showWidth.Text = string.Format("{0:0}px", left);
showWidth.Margin = new Thickness(left, 0, 0, 0);
}

关于.net - 获取文本框中字符的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13384969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com