如何:使用 ScrollViewer 创建 Expander

下面的示例演示如何创建包含图像和文本等复杂内容的 Expander 控件。 此示例还在 ScrollViewer 控件中包括 Expander 的内容。

示例

下面的示例演示如何创建 Expander。 此示例使用包含图像和文本的 BulletDecorator 控件,以便对 Header 进行定义。 ScrollViewer 控件提供滚动已展开内容的方法。

请注意,此示例设置的是 ScrollViewer(而不是内容)的 Height 属性。 如果设置的是内容的 Height,则 ScrollViewer 不允许用户滚动内容。 Width 属性是针对 Expander 控件设置的,并且此设置适用于 Header 和已展开的内容。

<Expander Width="200" HorizontalContentAlignment="Stretch">
   <Expander.Header>
     <BulletDecorator>
       <BulletDecorator.Bullet>
         <Image Width="10" Source="images\icon.jpg"/>
       </BulletDecorator.Bullet>
       <TextBlock Margin="20,0,0,0">My Expander</TextBlock>
     </BulletDecorator>
   </Expander.Header>
   <Expander.Content>
     <ScrollViewer Height="50">
       <TextBlock TextWrapping="Wrap">
         Lorem ipsum dolor sit amet, consectetur adipisicing elit, 
         sed do eiusmod tempor incididunt ut labore et dolore magna 
         aliqua. Ut enim ad minim veniam, quis nostrud exercitation 
         ullamco laboris nisi ut aliquip ex ea commodo consequat. 
         Duis aute irure dolor in reprehenderit in voluptate velit 
         esse cillum dolore eu fugiat nulla pariatur. Excepteur sint 
         occaecat cupidatat non proident, sunt in culpa qui officia 
         deserunt mollit anim id est laborum.
       </TextBlock>
     </ScrollViewer>
   </Expander.Content>
 </Expander>
//Create Expander object
Expander exp = new Expander();

//Create Bullet Panel for Expander Header
BulletDecorator bp = new BulletDecorator();
Image i = new Image();
BitmapImage bi= new BitmapImage(); 
bi.UriSource = new Uri(@"pack://application:,,/images/icon.jpg");
i.Source = bi;
i.Width = 10;
bp.Bullet = i;
TextBlock tb = new TextBlock();
tb.Text = "My Expander";
tb.Margin = new Thickness(20,0,0,0);     
bp.Child = tb;
exp.Header = bp;

//Create TextBlock with ScrollViewer for Expander Content
StackPanel spScroll = new StackPanel();
TextBlock tbc = new TextBlock();
tbc.Text =
        "Lorem ipsum dolor sit amet, consectetur adipisicing elit," +
        "sed do eiusmod tempor incididunt ut labore et dolore magna" +
        "aliqua. Ut enim ad minim veniam, quis nostrud exercitation" +
        "ullamco laboris nisi ut aliquip ex ea commodo consequat." +
        "Duis aute irure dolor in reprehenderit in voluptate velit" +
        "esse cillum dolore eu fugiat nulla pariatur. Excepteur sint" +
        "occaecat cupidatat non proident, sunt in culpa qui officia" +
        "deserunt mollit anim id est laborum.";
tbc.TextWrapping = TextWrapping.Wrap;

spScroll.Children.Add(tbc);
ScrollViewer scr = new ScrollViewer();
scr.Content = spScroll;
scr.Height = 50;
exp.Content = scr;

exp.Width=200;  
exp.HorizontalContentAlignment= HorizontalAlignment.Stretch;

请参见

参考

Expander

概念

Expander 概述

其他资源

Expander 帮助主题