3

I'm looking to create a single line textbox in WPF with a very precise width (in pixels), with no scrolling or overflow text. The width should be able to be set in pixels, not units (96/inch). I want the user to be unable to add additional characters to the textbox if the current text fills the textbox entirely.

What sort of properties should I set to get behavior as described above?

ford
  • 1,839
  • 3
  • 20
  • 38
  • I'm not familiar with WPF, but if you know the font type and size beforehand, could you leverage the maxlength attribute? – James Johnson Oct 10 '11 at 21:16
  • WPF doesn't work with pixels. You have to work with device independent units. See this http://stackoverflow.com/questions/1918877/how-can-i-get-the-dpi-in-wpf – Matěj Zábský Oct 10 '11 at 21:26

1 Answers1

1

You can set the MaxLength property of your textbox like this(It will restrict the length of text to 3 in your textbox) -

<TextBox MaxLength="3"/>

You can even bind this property with your own ViewModel property. In case you want to bind it to the width of your textbox if you don't want to hardcode the value you can bind it to Actual Width of your textbox -

<TextBox MaxLength="{Binding ActualWidth, RelativeSource={RelativeSource Mode=Self}}"/>
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
  • But since Actual Width will be in pixels, so you have to write a converter for some sort of calculation based on DPI and width of your control which will return the correct max length for your control. – Rohit Vats Oct 11 '11 at 07:54
  • Otherwise you can have a constant field in your ViewModel, i you know beforehand that what size will fit. Simply bind it to that property. – Rohit Vats Oct 11 '11 at 07:58
  • It looks like going for exact pixel counts will work contrary to how WPF wants to work. I'll go for the next best option: restricting character count. – ford Oct 11 '11 at 23:55