您的位置:首页 > 其它

意外地解决了一个WPF布局问题

2014-03-04 00:32 253 查看
原文:意外地解决了一个WPF布局问题今天做了一个小测试,意外地将之前的一个困扰解决了,原问题见《WPF疑难杂症会诊》中的“怎么才能禁止内容撑大容器?”

以前我是在外侧嵌套Canvas容器来解决的,这样实际上就是强制舍去了溢出部分,如果想实现多余的文字转变为省略号就办不到了,而且渐变的结束点也是随内容扩展到容器外面了。

现在改良为下面这段代码,就达到了很好的效果:

Code

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Page.Resources>

<Style TargetType="ListBoxItem">

<Setter Property="Template">

<Setter.Value>

<ControlTemplate TargetType="ListBoxItem">

<Border>

<Border.Background>

<LinearGradientBrush StartPoint="0,0" EndPoint="1,0">

<GradientStop Offset="0" Color="OrangeRed"/>

<GradientStop Offset="1" Color="Brown"/>

</LinearGradientBrush>

</Border.Background>

<TextBlock Text="{TemplateBinding Content}" TextTrimming="CharacterEllipsis"/>

</Border>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

<Style TargetType="ListBox">

<Setter Property="Template">

<Setter.Value>

<ControlTemplate>

<ScrollViewer BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">

<Viewbox VerticalAlignment="Top">

<StackPanel Width="{TemplateBinding Width}" IsItemsHost="True"/>

</Viewbox>

</ScrollViewer>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

</Page.Resources>

<WrapPanel>

<ListBox

Width="120"

Height="220"

Margin="8"

BorderBrush="Blue"

BorderThickness="3"

HorizontalContentAlignment="Stretch">

<ListBoxItem>1111111111

</ListBoxItem>

<ListBoxItem>22222222222222222222

</ListBoxItem>

<ListBoxItem>333333333333333333333333333333333333

</ListBoxItem>

<ListBoxItem>44444444444444444444444444444444444444444

</ListBoxItem>

</ListBox>

<ListBox

Width="180"

Height="220"

Margin="8"

BorderBrush="Green"

BorderThickness="3"

HorizontalContentAlignment="Stretch">

<ListBoxItem>1111111111

</ListBoxItem>

<ListBoxItem>22222222222222222222

</ListBoxItem>

<ListBoxItem>333333333333333333333333333333333333

</ListBoxItem>

<ListBoxItem>44444444444444444444444444444444444444444

</ListBoxItem>

</ListBox>

</WrapPanel>

</Page>

效果:



在这里我为ListBox也重定义了一个模板,为其ListBoxItem宿主容器StackPanel设置了宽度绑定,到这里仍然无法解决问题,过宽的内容还是毫不客气地超出容器宽度,并带出横向滚动条。

然后我又在StackPanel外围加了一个ViewBox,问题就被神奇地解决了,而我自己还是一头雾水~~

另外随之而来了一个新问题,看我在模板里设置了边框的绑定属性:“<ScrollViewer BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">”,在ListBox的定义处也曾为它们制定过不同颜色的3像素边框,但是这不起作用了,怎么设置都看不到ListBox的边框~不知道是怎么回事。

谁能解释一下灵异现象么~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: