WPF RibbonTextBox Width problem
It seems to me that the Ribbon control has a problem with textboxes. I was expecting a common TextBox control behaviour: a fixed width and a visible caret when the text exceeds the width. But the RibbonTextBox control changes its width and when the text exceeds the right limit, the overflow is not visible.
I found a hack on a blog that does something like this:
var img = SearchButton.Template.FindName("image", SearchButton);
if开发者_StackOverflow社区 (img != null && img is Image)
(img as Image).Visibility = Visibility.Collapsed;
var lbl = FindTemplateControl<Label>(SearchText);
var border = SearchText.Template.FindName("Bd", SearchText);
if (border != null && border is Border && img != null && lbl != null)
{
(border as Border).Width = SearchText.ActualWidth - (((Image)img).ActualWidth + lbl.ActualWidth);
}
but I reallly don't want to do such a workaround. Is there any other simpler way to achieve simple TextBox behaviour?
There is a Property "TextBoxWidth" which is not shown in the designer but can be used also in XAML:
<ribbon:RibbonTextBox Label="abc" TextBoxWidth="300" />
Apparently, the RibbonTextBox isn't a simple TextBox; it's actually a stackpanel with: image + label + border. Actually, its template has this content:
<RibbonTextBox>
<StackPanel>
<Image/>
<Label>
<Border>
<ContentPresenter>
<TextBlock/>
</ContentPresenter>
</Border>
</Label>
<Border>
<ScrollViewer>
<Grid>
<Rectangle>
</Rectangle>
<ScrollContentPresenter>
<TextBoxView>
<DrawingVisual/>
</TextBoxView>
<AdornerLayer/>
</ScrollContentPresenter>
<ScrollBar/>
<ScrollBar/>
</Grid>
</ScrollViewer>
</Border>
</StackPanel>
</RibbonTextBox>
So, when you set the width of a RibbonTextBox, you don't actually set the width of the textbox, but the entire control's width.
My suggestion would be to create a class that derives from RibbonTextBox and implement in this class the Loaded event handler just like the example you gave in your post. But keep in mind that the image, label and border have additional margin and padding which will give you extra space on the left of the textbox.
You can set width like this:
var textBox = new RibbonTextBox() { Label = "Label", Text = "Text", TextBoxWidth = 150 };
The problem with RibbonTextBox is that the KeyDown and KeyUp event are not triggered when you press "enter" key. As an result, the LostFocus()
event is not triggered when you press the "enter" key.
精彩评论