views:

59

answers:

1

I am using Silverlight 2 to dynamically add a TextBlock to a Canvas. I set the MaxWidth of the TextBlock but it ignores this value and displays a string longer than the MaxWidth value.

TextBlock label=new TextBlock();
label.SetValue(Canvas.LeftProperty,Convert.ToDouble(x+3));
label.SetValue(Canvas.TopProperty, Convert.ToDouble(y + 1));
label.Width = DisplayWidth - 6;
label.Height = DisplayHeight - 2;
label.TextWrapping = TextWrapping.NoWrap;
label.MaxWidth = DisplayWidth-6;
label.MinWidth = DisplayWidth-6;
label.Text = this.Title;
label.Margin = new Thickness(3.0);
baseCanvas.Children.Add(label);

What do I have to do to get the TextBlock to restrict its width to a specific value? Ideally I'll add conditional ellipses too (i.e. ...).

+1  A: 

It would seem that MaxWidth on a TextBlock is ineffectual when the TextBlock is a direct child of a Canvas. I can't quite fathom why that would be so. However the solution would be to place the TextBlock in a Border:-

TextBlock label=new TextBlock(); 
label.SetValue(Canvas.LeftProperty,Convert.ToDouble(x+3)); 
label.SetValue(Canvas.TopProperty, Convert.ToDouble(y + 1)); 
label.Width = DisplayWidth - 6; 
label.Height = DisplayHeight - 2; 
label.TextWrapping = TextWrapping.NoWrap; 
label.MaxWidth = DisplayWidth-6; 
label.MinWidth = DisplayWidth-6; 
label.Text = this.Title; 
label.Margin = new Thickness(3.0); 
Border border = new Border();
border.Child = label;
baseCanvas.Children.Add(border); 

The Border will honor the MaxWidth of the TextBlock but since it is given no thickness the border itself is invisible.

AnthonyWJones
Works a treat - thanks very much.
DEH