0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【WPF】スライダーのカーソル位置に同期してウィンドウのサイズを変える

Posted at

なにをするのか

WPFデスクトップアプリのスライダーコントロールを使う
スライダーのカーソル位置に応じて、ウィンドウのサイズを変える

つくったもの

画面とソースコードを載せる

※動いている画面の録画を試みたが、Win+Gの標準録画機能はつかえなかった
※理由:ウィンドウサイズが変更されると録画が停止されるため

画面

アプリ起動時

300 x 300の画面が表示される
画面には2つのスライダーが配置される
1.png

ピンクのスライダーを右に動かすと、ウィンドウが縦に伸びる
2.png

水色のスライダーを下に動かすと、ウィンドウが横に伸びる
3.png

当初は「横スライダー=ウィンドウ横サイズ」として対応付けていたが
ウィンドウサイズ変更にともなってスライダーの幅も変わり、描画がカクつくので
上記のような割り当てとした。

XAMLソースコード

MainWindow.xamlの内容を載せる

MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="{Binding Value, ElementName=HorizontalSlider, Mode=TwoWay}"
        Width="{Binding Value, ElementName=VerticalSlider, Mode=TwoWay}">
    <DockPanel LastChildFill="False">
        <!--水平方向のスライダー-->
        <StackPanel DockPanel.Dock="Top" Margin="5" Background="LightPink">
            <Slider x:Name="HorizontalSlider" Value="300" Minimum="300" Maximum="700"/>
            <TextBlock Text="{Binding Value, ElementName=HorizontalSlider, StringFormat={}{0:N1}}"/>
        </StackPanel>

        <!--垂直方向のスライダー-->
        <StackPanel DockPanel.Dock="Left" Orientation="Horizontal" Margin="5" Background="LightBlue">
            <Slider x:Name="VerticalSlider" Value="300" Minimum="300" Maximum="700" Orientation="Vertical" IsDirectionReversed="True"/>
            <TextBlock Text="{Binding Value, ElementName=VerticalSlider, StringFormat={}{0:N1}}"/>
        </StackPanel>
    </DockPanel>
</Window>

コードビハインドは変更していない

XAMLのポイント

  • ウィンドウの高さ・幅はMode=TwoWayとする
  • 縦スライダーは上が若い番号になるようにIsDirectionReversed="True"とする
  • テキストブロックにStringFormat={}{0:N1}を設定する
    • 未指定の場合、少数表示時にドックの幅が広くなる(下画像)

4.png

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?