3
0

More than 5 years have passed since last update.

【WPF】ItemsControlで、複数のControlを重ねて表示する

Posted at

やりたいこと

画面上に、複数の線を描きたいときに、Polylineを使おうと思ったが、画面のxamlに「Polyline・・」を何個(何十個)も書きたくないので、コレクションにPolylineをAddするだけで画面に線を追加したい。

結果

ItemsControl.ItemsPanelにItemsPanelTemplateを入れて、「Grid」や「Canvas」を指定するとできる。
具体的には、下記のようにする。

MainWindwo.xaml
<ItemsControl ItemsSource="{Binding Pl}" Width="600" Height="600">
    <ItemsControl.Template>
        <ControlTemplate TargetType="ItemsControl">
            <ItemsPresenter Margin="10" />
        </ControlTemplate>
    </ItemsControl.Template>

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <!-- ここに、Gridを指定する。-->
            <Grid />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

バインドしたプロパティをもつViewModelは下記のようにしている。

ViewModel.cs
namespace WpfApp1
{
    class ViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        // ItemsControlのSourceに設定するコレクション
        public ObservableCollection<Polyline> Pl { get { return pl; } }
        public ObservableCollection<Polyline> pl = new ObservableCollection<Polyline>();

        // DataTemplateの中にバインドしたいプロパティ
        public Thickness MyThickness { get; } = new Thickness(20);

        public ViewModel()
        {
            Polyline pl1 = new Polyline();
            pl1.Points.Add(new Point(10, 10));
            pl1.Points.Add(new Point(200, 150));
            pl1.Stroke = new SolidColorBrush(Colors.Red);
            pl1.StrokeThickness = 5;
            pl.Add(pl1);

            Polyline pl2 = new Polyline();
            pl2.Points.Add(new Point(15, 15));
            pl2.Points.Add(new Point(250, 600));
            pl2.Points.Add(new Point(600, 400));
            pl2.Stroke = new SolidColorBrush(Colors.Yellow);
            pl2.StrokeThickness = 5;
            pl.Add(pl2);
        }
    }
}

上記を実行すると、下記のようになる。
image.png

ItemsControlについて

ItemsControlは、ListBoxの継承元のクラス。使い方は、下記を参照。
https://qiita.com/tera1707/items/363d2a33eadcb3eb275a

Gridでないものを指定したとき

ListBoxを使う場合など、普通は縦や横に項目を並べたいと思うので、Gridではなく、StackPanelやWrapPanelを指定すると思う。
例えばStackPanelを指定すると、こうなる。
(2つのPolylineが、縦に並んでいる)
image.png

参考

自分のページ(ListBox関連)
https://qiita.com/tera1707/items/363d2a33eadcb3eb275a

ItemsControl 攻略 ~ 外観のカスタマイズ
http://grabacr.net/archives/1240

コード

3
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
3
0