共用方式為


如何:使用 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;

另請參閱