WPF memo - arosh/arosh.github.com GitHub Wiki

Panel

<Window x:Class="Tutrial.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Width="550" Height="500" >

    <!--
    WPFにおけるパネルのお勉強
    
    * Canvas
    
    左上からの相対座標で子要素を配置できる。それだけ。
    相対座標は負の値も指定できることに注目。
    
    * Grid
    格子内に子要素を配置できる。
    RowDefinitions(Heightを指定)とColumnDefinitions(Widthを指定)プロパティの要素数で決められる。
    プロパティを"Auto"にすると子要素のサイズで格子の大きさが決まり、
    "*"にすると、残り全てのあまりが均等に割り振られる。
    このとき、"2*"と指定すれば、"*"の2倍ふられることに注目
    すべてのセルの大きさが均一な、UniformGridというのもある。
    
    * DockPanel
    
    子要素がいずれかの端にドッキングしようとする(子要素のDockPanel.Dockで指定)。
    子要素を並べる順番が意外に重要である。
    開いた部分には最後に描写した要素が埋まる仕様なので、LastChildFill="False"を指定せよ。
    
    * StackPanel
    
    子要素を縦または横に順番に並べていく。
    Orientationプロパティで方向を指定する。
    VirtualizingStackPanel.IsVirtualizing="True" を指定すると、
    見えない要素を描画してパフォーマンスを上げようと努力する。
    
    * WrapPanel
    
    左から右に子要素を並べる。
    右端に来たら、折り返して左から並べ直し。
    メニューバーや、アイコンの類を並べるのに向いている。
    専ら縦幅が変更されるので、Gridで使うときはHeight="Auto"を推奨
    
    レイアウトに関連するプロパティ
    
    * Width Height {(Max|Min)(Width|Height)}
    
    説明不要
    
    * (Horizontal|Vertical)Alignment
    
    親要素の(左右|左右)どちら側に揃えるのかを指定。
    デフォルトはどちらも"Stretch"で、親要素いっぱいに広がろうとする。
    設定できる値は、Top、Bottom、Left、Right、Centerなど
    
    * Margin Padding
    HTMLとほぼ一緒。必ず上下左右4つ指定しないとダメなのかな?(="5,0,5,0")
    負の値も指定できる。
    
    * LayoutTransform
    
    拡大縮小や回転などが行える。ググれ。
    
    * ZIndex
    
    要素の深度を指定できる。大きいほうが優先される
    
    * Visibility
    
    Visibleは見える
    Hiddenは見えないけど、スペースは残っている
    Collapsedはスペースすら残らない
    
    -->

    <Grid>
        <!-- グリッドレイアウトの設定 -->
        <!-- メニュー類は、ウィンドウのサイズを変更した際に折りたたまれるWrapPanelを使っているので、高さが勝手に変わる → Auto -->
        <!-- 発言ログはウィンドウを大きくした際にも一番大きくなるように、残り全てを割り当てる -->
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
            <RowDefinition Height="100" />
            <RowDefinition Height="30" />
        </Grid.RowDefinitions>

        <!-- WrapPanelのBackgroundとMenuのBackgroundを一緒にすると、多少はキレイに見える -->
        <WrapPanel Grid.Row="0" Background="Yellow">
            <Menu Background="Yellow">
                <MenuItem Header="ファイル" />
                <MenuItem Header="コンタクト" />
                <MenuItem Header="アクション" />
                <MenuItem Header="ツール" />
                <MenuItem Header="ヘルプ" />
            </Menu>
        </WrapPanel>

        <!-- WrapPanelのOrientationもStackPanelと同じように配置方向を決められるが、デフォルト値はHorizontalなので、指定しても特に意味は無い -->
        <WrapPanel Grid.Row="1" Background="Orange" Orientation="Horizontal">
            <!-- 全部設定するのが面倒なので、スタイルを利用 -->
            <WrapPanel.Resources>
                <Style TargetType="Button">
                    <Setter Property="Margin" Value="10" />
                    <Setter Property="Width" Value="100" />
                </Style>
            </WrapPanel.Resources>

            <Button Content="招待" />
            <Button Content="ファイル送信" />
            <Button Content="ウェブカム" />
            <Button Content="オーディオ" />
        </WrapPanel>

        <Label Grid.Row="2" Background="LightBlue">
            Contact Info
        </Label>

        <Border Grid.Row="3" Background="Lime">

            <!-- ListBoxItemは左の辺に張り付き、幅いっぱいに広がる -->
            <!-- どこにDockPanelが? -->
            <ListBox Margin="20" DockPanel.Dock="Left" HorizontalAlignment="Stretch">
                <ListBoxItem>Conversation1</ListBoxItem>
                <ListBoxItem>Conversation2</ListBoxItem>
            </ListBox>
        </Border>

        <!-- テキストボックスと送信ボタンのためにグリッドを使用 -->
        <Grid Grid.Row="4" Background="Red">

            <!-- 大きさが3:1の割合になるように -->
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="3*" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>

            <TextBox Grid.Column="0" Margin="20" Foreground="Blue" Background="White" TextWrapping="Wrap"></TextBox>
            <Button Grid.Column="1" Content="送信" Margin="20" />
        </Grid>

        <Label Grid.Row="5" Background="Gray">
            Status Bar
        </Label>
    </Grid>
</Window>

Image

<Window x:Class="Image.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="680">
    
    <!--
    ImageにはStretchプロパティを指定できる
    None: 拡大縮小をいっさいしない
    Fill: 全体を埋める。縦横比が変形
    Uniform: 縦横比が保持できる範囲で拡大縮小する。余ったところには余白ができる
    UniformToFill: 縦横比を保持した状態で、全体を埋める。(すなわち、一部が切り取られる)
    -->
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*" />
            <ColumnDefinition Width="2*" />
        </Grid.ColumnDefinitions>
        <Image Grid.Row="0" Grid.Column="0" Source="Desert Landscape.jpg" Stretch="Uniform" />
        <Image Grid.Row="1" Grid.Column="0">
            <Image.Source>
                <BitmapImage UriSource="Waterfall.jpg" DecodePixelWidth="100" />
            </Image.Source>
            
            <Image.Clip>
                <EllipseGeometry  Center="50,40" RadiusX="40" RadiusY="30"   />
            </Image.Clip>
        </Image>
        <Image Name="Image" Grid.Row="2" Grid.Column="0"  Stretch="Uniform" />

        <StackPanel  Grid.Row="2" Grid.Column="1">
            <StackPanel.Resources>
                <Style TargetType="Label">
                    <Setter Property="HorizontalAlignment" Value="Center" />
                </Style>
            </StackPanel.Resources>
            <Label Name="LabelCamera" />
            <Label Name="LabelDate" />
            <Label Name="LabelIso" />
        </StackPanel>
    </Grid>
</Window>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;

namespace Image
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var stream = new FileStream("C:\\Users\\Public\\Pictures\\Sample Pictures\\Humpback Whale.jpg", FileMode.Open);

            var decoder = new JpegBitmapDecoder(
                stream, BitmapCreateOptions.PreservePixelFormat,
                BitmapCacheOption.Default);

            var bitmapSource = decoder.Frames[0];

            Image.Source = bitmapSource;

            var bmf = BitmapFrame.Create(bitmapSource);
            var metadata = bmf.Metadata as BitmapMetadata;

            LabelCamera.Content = "カメラ: " + metadata.CameraModel;
            LabelDate.Content = "撮影日: " + metadata.DateTaken;
            LabelIso.Content = "ISO: " + "難しい処理";
        }
    }
}

Graphics

<Window x:Class="Graphics.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    
    <!--
    WPFにおけるグラフィックスのお勉強
    
    Shapeの具象クラス
    
    * Ellipse 楕円
    * Rectangle 短形(長方形)
    * Line 直線
    * Polyline 連続直線
    * Path パス(Geometryと一緒に使う)
    * Polygon 多角形
    
    Shapeはそのまま置ける
    
    Geometryは図形のみ。(色や線の太ささえ書けない)
    Pathの中に(キャンバス的に)Geometry~クラスを置ける
    
    PathGeometryは複雑な図形を書くための?もの。
    PathGeometry.Figure内に、
    * LineSegment
    * PolyLineSegment
    * ArcSegment
    * BezierSegment
    * PolyBezierSegment
    などの直線がかけるデータがある
    -->
    <Canvas>
        <Path Fill="Red" Stroke="Black" StrokeThickness="4">
            <Path.Data>
                <PathGeometry>
                    <PathGeometry.Figures>
                        <PathFigure StartPoint="0,0" IsClosed="True">
                            <PathFigure.Segments>
                                <LineSegment Point="0,300" />
                                <LineSegment Point="400,300" />
                                <LineSegment Point="400,0" />
                            </PathFigure.Segments>
                        </PathFigure>
                    </PathGeometry.Figures>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Canvas>
</Window>

Control

<Window x:Class="コントロール.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="480" Width="640">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <WrapPanel Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2">
            <Menu>
                <MenuItem Command="Paste" />
                <MenuItem Command="Find" />
            </Menu>
        </WrapPanel>

        <TextBox Grid.Row="1" Grid.Column="0" BorderBrush="Black" BorderThickness="2" Margin="10" TextWrapping="Wrap">
            objectには呼び出し元のコントロール情報、そしてRouteEventArgsにはイベントに関する情報が格納されます。
            メソッドの中では、これらの引数からイベント発生もとの情報を取得することができます。
            
            ボタンの上にグラフィック要素を乗せたりすると、イベントの管理が大変になる(最前面のオブジェクトに対してイベントが発生するため)。
            そのため、プログラミング言語における例外のように、外側の要素でイベントをキャッチできる機能がある(イベントルーティング)
            
            イベントルーティングの種類
            * バブル型 下から上に
            * トンネル型 上から下に
            * 直接方 その要素だけに (種類は少ない)
            
            あるイベントが発生する前に、Preview#{イベント名} というトンネル型イベントが発生する。前処理や、イベントの発生をとめるときに使用する
        </TextBox>

        <Button Grid.Row="2" Name="btn" Click="btn_Click">
            <Ellipse Fill="Aqua" Stroke="Black" Width="200" Height="100" />
        </Button>

        <StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
            <StackPanel>
                <CheckBox Content="チェックボックス" />
            </StackPanel>
            <StackPanel>
                <!--
                RadioButtonは基本的には、同じ階層のものを同じグループとみなす。
                別のグループにしたいときには、GroupNameプロパティを設定する
                -->
                <RadioButton Content="" />
                <RadioButton Content="" />
                <RadioButton GroupName="明るさ" Content="明るい" />
                <RadioButton GroupName="明るさ" Content="暗い" />
            </StackPanel>
        </StackPanel>
    </Grid>
</Window>
<Window x:Class="コントロール2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <!--
        MenuのHeaderプロパティで_に続けて設定されたアルファベット1文字が自動的にショートカットキーになる
        よく知らないが、チェックをつけることができるらしい。
        -->
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Menu Grid.Row="0">
            <MenuItem Header="ファイル(_F)">
                <!--
                IntputGestureTextはショートカットキーを"表示するだけ"
                -->
                <MenuItem Header="新規(_N)" IsCheckable="True" InputGestureText="Ctrl+X" />
                <MenuItem Header="開く(_O)" />
                <MenuItem Header="閉じる(_C)" />
                <Separator />
                <MenuItem Header="サブメニュー">
                    <MenuItem Header="サブメニュー1(_S)"/>
                    <MenuItem Header="サブメニュー2"/>
                </MenuItem>
                <Separator />
                <MenuItem Header="チェック" IsCheckable="True" />

                <MenuItem Header="ツールチップつき" >
                    <MenuItem.ToolTip>
                        <ToolTip>
                            ツールチップ情報
                        </ToolTip>
                    </MenuItem.ToolTip>
                </MenuItem>
            </MenuItem>
        </Menu>

        <ToolBarTray Grid.Row="1">
            <ToolBar>
                <Button Content="新規" Command="New" />
                <Button Content="開く" Command="Open" />
                <Button Content="保存" Command="Save" />
                <Separator />
                <Button Content="切り取り" Command="Cut" />
                <Button Content="コピー" Command="Copy" />
                <Button Content="貼り付け" Command="Paste" />
            </ToolBar>
        </ToolBarTray>

        <Canvas Grid.Row="2">
            <Rectangle Width="200" Height="100" Fill="Cyan">
                <Rectangle.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="ほげ" />
                        <MenuItem Header="ふが">
                            <MenuItem Header="ふー" />
                            <MenuItem Header="ばー" />
                        </MenuItem>
                    </ContextMenu>
                </Rectangle.ContextMenu>
            </Rectangle>
        </Canvas>
    </Grid>
</Window>
<!--
ResizeMode: サイズ変更ができるかどうか
TopMost: 常に最善面表示する

-->    
<Window x:Class="コントロール3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <ToolBarTray Grid.Row="0" Background="White">
                <ToolBar Band="1" BandIndex="1">
                    <ToolBarPanel Background="Red" Orientation="Horizontal">
                        <Button>新規</Button>
                        <Button>開く</Button>
                    </ToolBarPanel>
                    <ToolBarPanel Orientation="Vertical">
                        <Button>保存</Button>
                        <Button>名前をつけて保存...</Button>
                    </ToolBarPanel>
                    <ToolBarPanel Orientation="Horizontal" ToolBar.OverflowMode="Always">
                        <Button>切り取り</Button>
                        <Button>コピー</Button>
                        <Button>貼り付け</Button>
                    </ToolBarPanel>
                </ToolBar>
            </ToolBarTray>

            <StackPanel Grid.Row="1"   Margin="10" Orientation="Vertical">
                <!--
            ラベルは、Contentの_に続けた文字がショートカットキーになる(ALTと組み合わせて)
            targetプロパティで、フォーカスのショートカットキーとして使える
            -->
                <WrapPanel>
                    <Label Target="{Binding ElementName=tb}" Content="ファイル(_F)" />
                    <TextBox Name="tb" Width="50" />
                </WrapPanel>

                <!--
            TextBoxは装飾機能なし
            TextBlockには装飾機能があるが、表示するだけ
            RichTextBoxは、装飾も編集もできる
            
            TextBoxには入力規定が設定できる
            * AcceptsDigitsOnly 数値だけ
            * AcceptsReturn 改行を許可
            * AcceptsTab タブ文字を許可
            * CharacterCasing 大文字小文字に強制的に変換
            
            Widthは表示される幅
            MaxLengthは最大文字数
            -->
                <WrapPanel>
                    <Label Target="{Binding ElementName=tbl}" Content="テキスト(_T)" />
                    <TextBlock Name="tbl">TextBlockコントロールによるテキスト</TextBlock>
                </WrapPanel>

                <WrapPanel>
                    <Label Target="{Binding ElementName=pw}" Content="パスワード(_P)" />
                    <PasswordBox Name="pw" Width="50" />
                </WrapPanel>
                <ComboBox>
                    <ComboBoxItem Content="プレーンテキスト" />
                    <ComboBoxItem>
                        <Rectangle Width="60" Height="20" Fill="Blue" />
                    </ComboBoxItem>
                    <ComboBoxItem>
                        <Bold>
                            <Italic>
                                リッチテキスト
                            </Italic>
                        </Bold>
                    </ComboBoxItem>
                </ComboBox>

                <!--
            SelectionMode="Extended" は、Shiftキーを押したときだけ複数選択
            -->
                <ListBox Height="50" Width="130" SelectionMode="Single">
                    <ListBoxItem>プレーンテキスト</ListBoxItem>
                    <ListBoxItem>
                        <Rectangle Width="60" Height="20" Fill="Blue" />
                    </ListBoxItem>
                    <ListBoxItem>
                        <Bold>
                            <Italic>リッチテキスト</Italic>
                        </Bold>
                    </ListBoxItem>
                </ListBox>
                <TabControl TabStripPlacement="Top">
                    <TabItem Name="t1" Header="ほげ関係">ほげ</TabItem>
                    <TabItem Name="t2" Header="ふが関係">ふが</TabItem>
                </TabControl>
                <WrapPanel>
                    <TextBox Text="{Binding ElementName=slider, Path=Value}" Width="50" />
                    <Slider Name="slider" Minimum="0" Maximum="255" Value="128" Width="100" AutoToolTipPlacement="TopLeft" AutoToolTipPrecision="0" />
                </WrapPanel>
            </StackPanel>
        </Grid>
    </ScrollViewer>
</Window>
⚠️ **GitHub.com Fallback** ⚠️