答案 0 :(得分:2)
(编辑: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);
}