HOW TO:使用 ScrollViewer 建立 Expander
更新:2007 年 11 月
本範例顯示如何建立含有複雜內容 (例如影像和文字) 的 Expander 控制項。本範例也會將 Expander 的內容放在 ScrollViewer 控制項。
範例
下列範例顯示如何建立 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;