LoginSignup
9
7

More than 5 years have passed since last update.

UWP・WPFメモ データバインディング

Last updated at Posted at 2017-01-04

UWP

UWPサンプル1

u01.png

MainPage.xaml
<Page
    x:Class="UwpApp1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp1"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Slider x:Name="slider" Value="30" Maximum="100" Margin="0,15,0,0"/>
        <ProgressBar Height="10" Value="{Binding ElementName=slider,Path=Value}" Maximum="100" Margin="0,15,0,0"/>
        <TextBox Text="{Binding ElementName=slider,Path=Value,Mode=TwoWay}" Margin="0,15,0,0"/>
    </StackPanel>
</Page>

UWPサンプル2(コレクション)

u02.png

MainPage.xaml
<Page
    x:Class="UwpApp2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp2"
    xmlns:vm="using:UwpApp2.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.DataContext>
        <vm:PersonVM />
    </Page.DataContext>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <!-- 左側:そのまま表示 -->
        <ListBox Grid.Column="0" ItemsSource="{Binding Path=Persons}" DisplayMemberPath="Name" />

        <!-- 右側:表示をカスタマイズ -->
        <ListBox Grid.Column="1" ItemsSource="{Binding Path=Persons}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
                        <TextBlock Text="{Binding Memo}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Page>
PersonVM.cs
using System.Collections.Generic;
using UwpApp2.Models;

namespace UwpApp2.ViewModels
{
    public class PersonVM
    {
        // リスト内容の変更に対応する場合は
        // List の代わりに System.Collections.ObjectModel.ObservableCollection を使う
        public List<Person> Persons { get; set; }

        public PersonVM()
        {
            this.Persons = new List<Person>();

            this.Persons.Add(new Person { Name = "太郎", Age = 10, Memo = "あいうえお" });
            this.Persons.Add(new Person { Name = "次郎", Age = 8, Memo = "aaa" });
            this.Persons.Add(new Person { Name = "三郎", Age = 3, Memo = "123456" });
        }
    }
}
Person.cs
namespace UwpApp2.Models
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Memo { get; set; }
    }
}

UWPサンプル3(コンバーター)

u03.png

MainPage.xaml
<Page
    x:Class="UwpApp3.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp3"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <Page.Resources>
        <local:BooleanToMessageConverter x:Key="BoolToMsgConv"/>
    </Page.Resources>

    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <CheckBox x:Name="checkbox" Content="表示" IsChecked="True" Margin="0,15,0,0"/>

        <!-- Windows 10、バージョン1607以降はXAMLフレームワークにbool値とVisibility値のコンバーターが組み込まれている -->
        <Button Content="ボタン" Visibility="{Binding ElementName=checkbox,Path=IsChecked}" Margin="0,15,0,0"/>

        <TextBlock Text="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource BoolToMsgConv}}" Margin="0,15,0,0"/>
    </StackPanel>
</Page>
BooleanToMessageConverter.cs
using System;

namespace UwpApp3
{
    /// <summary>
    /// 真偽値からメッセージへ変換
    /// </summary>
    public class BooleanToMessageConverter : Windows.UI.Xaml.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value is bool && (bool)value)
            {
                return "Trueです。";
            }
            else
            {
                return "Falseです。";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
}

UWPサンプル4(コンパイル時バインディング)

u04.png

MainPage.xaml
<Page
    x:Class="UwpApp4.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:UwpApp4"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    <StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock Text="{x:Bind Message1,Mode=TwoWay}" Margin="0,15,0,0" />
        <Button Content="ボタン" Click="{x:Bind Button_Click}" Margin="0,15,0,0" />
    </StackPanel>
</Page>
MainPage.xaml.cs
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 を参照してください

namespace UwpApp4
{
    /// <summary>
    /// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public static readonly DependencyProperty Message1Property = 
            DependencyProperty.Register(
              "Message1",
              typeof(string),
              typeof(MainPage),
              new PropertyMetadata(null)
            );
        public string Message1
        {
            get { return (string)GetValue(Message1Property); }
            set { SetValue(Message1Property, (string)value); }
        }

        public MainPage()
        {
            this.InitializeComponent();
            this.Message1 = "こんにちは";
        }

        public void Button_Click(object sender, RoutedEventArgs e)
        {
            this.Message1 = "さようなら";
        }
    }
}

WPF

WPFサンプル1

w01.png

MainWindow.xaml
<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>
        <Slider x:Name="slider" Value="30" Interval="1" IsSnapToTickEnabled="True" Maximum="100" Margin="0,15,0,0"/>
        <ProgressBar Height="10" Value="{Binding ElementName=slider,Path=Value}" Maximum="100" Margin="0,15,0,0"/>
        <TextBox Text="{Binding ElementName=slider,Path=Value,Mode=TwoWay}" Margin="0,15,0,0"/>
    </StackPanel>
</Window>

WPFサンプル2(コレクション)

w02.png

MainWindow.xaml
<Window x:Class="WpfApplication2.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:WpfApplication2"
        xmlns:vm="clr-namespace:WpfApplication2.ViewModels"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <vm:PersonVM />
    </Window.DataContext>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <!-- 左側:そのまま表示 -->
        <ListBox Grid.Column="0" ItemsSource="{Binding Path=Persons}" DisplayMemberPath="Name" />

        <!-- 右側:表示をカスタマイズ -->
        <ListBox Grid.Column="1" ItemsSource="{Binding Path=Persons}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Name}" FontWeight="Bold"/>
                        <TextBlock Text="{Binding Memo}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>
PersonVM.cs
using System.Collections.Generic;
using WpfApplication2.Models;

namespace WpfApplication2.ViewModels
{
    public class PersonVM
    {
        // リスト内容の変更に対応する場合は
        // List の代わりに System.Collections.ObjectModel.ObservableCollection を使う
        public List<Person> Persons { get; set; }

        public PersonVM()
        {
            this.Persons = new List<Person>();

            this.Persons.Add(new Person { Name = "太郎", Age = 10, Memo = "あいうえお" });
            this.Persons.Add(new Person { Name = "次郎", Age = 8, Memo = "aaaa" });
            this.Persons.Add(new Person { Name = "三郎", Age = 3, Memo = "123456" });
        }
    }
}
Person.cs
namespace WpfApplication2.Models
{
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Memo { get; set; }
    }
}

WPFサンプル3(コンバーター)

w03.png

MainWindow.xaml
<Window x:Class="WpfApplication3.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:WpfApplication3"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <!-- System.Windows.Controls.BooleanToVisibilityConverterクラス -->
        <BooleanToVisibilityConverter x:Key="BoolToVisibilityConv"/>

        <local:BooleanToMessageConverter x:Key="BoolToMsgConv"/>
    </Window.Resources>

    <StackPanel>
        <CheckBox x:Name="checkbox" Content="表示" IsChecked="True" Margin="0,15,0,0"/>

        <Button Content="ボタン" Visibility="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource BoolToVisibilityConv}}" Margin="0,15,0,0"/>

        <TextBlock Text="{Binding ElementName=checkbox,Path=IsChecked,Converter={StaticResource BoolToMsgConv}}" Margin="0,15,0,0"/>
    </StackPanel>
</Window>
BooleanToMessageConverter.cs
using System;
using System.Globalization;

namespace WpfApplication3
{
    /// <summary>
    /// 真偽値からメッセージへ変換
    /// </summary>
    public class BooleanToMessageConverter : System.Windows.Data.IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool && (bool)value)
            {
                return "Trueです。";
            }
            else
            {
                return "Falseです。";
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

動作確認した環境

  • Windows 10 (バージョン1607), Visual Studio 2015

参考サイト

9
7
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
9
7