如何:使用 ScrollViewer 创建 Expander

此示例演示如何创建包含复杂内容(例如图像和文本)的 Expander 控件。 该示例还将 Expander 的内容包含在 ScrollViewer 控件中。

示例

以下示例演示如何创建 Expander。 该示例使用包含图像和文本的 BulletDecorator 控件来定义 HeaderScrollViewer 控件提供一种滚动展开内容的方法。

请注意,该示例在 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;

另请参阅