WPF ScrollViewerでスクロールできない時の解決法

WPFやってると画面の表示がうまくいかない時がよくあります。
今回は、ScrollViewerを使ってスクロールバーを表示したのに、スクロールできなかった時の話です。

スクロールできない時の画面

以下の画像ように、ScrollViewerを使ってスクロールバーを表示させました。
スクロールバーは正しい位置に表示されているのですが、画面と一緒にスクロールバーが伸びてしまっています。
スクロールバーが伸びているため、スクロールさせることができませんでした。

画面と一緒にスクロールバーが伸びている

右側にバーは出ていますが、ボタンと一緒に伸びてしまっていて機能しません。

コード

この時のコードはこちらです。

<Window x:Class=”WpfApplication1.MainWindow”
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
    xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
    xmlns:local=”clr-namespace:WpfApplication1″
    mc:Ignorable=”d”
    Title=”MainWindow” Height=”350″ Width=”525″>
    <StackPanel>
        <ScrollViewer>
            <local:OriginalButton/>
        </ScrollViewer>
    </StackPanel>
</Window>

↑MainWindow.xaml

<UserControl x:Class=”WpfApplication1.OriginalButton”
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
    xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
    xmlns:local=”clr-namespace:WpfApplication1″
    mc:Ignorable=”d”
    d:DesignHeight=”300″ d:DesignWidth=”300″>
    <StackPanel>
        <Button Height=”200″ Background=”AliceBlue”>
            <TextBlock Text=”1つ目のボタン” FontSize=”30″/>
        </Button>
        <Button Height=”180″ Background=”Plum”>
            <TextBlock Text=”2つ目のボタン
はみ出ている” FontSize=”30″/>
        </Button>
    </StackPanel>
</UserControl>

↑OriginalButton.xaml

原因と解決方法

ScrollViewerとOriginalButtonをStackPanelに入れていることが原因でした。
StackPanelからGridに置き換えてあげると、スクロールできるようになりました。

<Window x:Class=”WpfApplication1.MainWindow”
    xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation”
    xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”
    xmlns:d=”http://schemas.microsoft.com/expression/blend/2008″
    xmlns:mc=”http://schemas.openxmlformats.org/markup-compatibility/2006″
    xmlns:local=”clr-namespace:WpfApplication1″
    mc:Ignorable=”d”
    Title=”MainWindow” Height=”350″ Width=”525″>
    <Grid>
        <ScrollViewer>
            <local:OriginalButton/>
        </ScrollViewer>
    </Grid>
</Window>

↑修正したMainWindow.xaml

正しくスクロールバーが表示された

↑スクロールできるようになった画面

最後に & 関連書籍

分かりにくいところや「もっとこうしてほしい」などのご意見がありましたら、ツイッターから連絡いただけると幸いです。
質問に関してもお気軽にお問い合わせください。

以下の記事では、WPFのDataTemplateを使って、コントロール内に複数のコントロールを表示する方法を紹介しています。
興味があれば見てみてください。

以下は関連書籍です。

コメント

タイトルとURLをコピーしました