데이터 바인딩 6

트리거를 통해 XAML에서 기본적인 UI 제어가 가능하다.

Play 버튼을 클릭하면 Stop 버튼이 활성화 되고 Play 버튼이 비활성화 되고
Stop 버튼을 클릭하면 Play 버튼이 활성화 되고 Stop 버튼이 비활성화 되는 것을 만들어 보자.

Button.Style을 컨트롤당 하나씩 배치하고 있다.
트리거를 Style의 Style.Triggers 내부에 작성한다.

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal">
        <Button Content="Play" Height="23" Margin="5" Click="Execute_Click">
            <Button.Style>
                <Style TargetType="Button">
                    <Setter Property="IsEnabled" Value="True"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsRunning}" Value="True">
                            <Setter Property="IsEnabled" Value="False"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
        <Button Content="Stop" Height="23" Margin="5" Click="Stop_Click">
                                <Button.Style>
                <Style TargetType="Button">
                    <Setter Property="IsEnabled" Value="False"/>
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding IsRunning}" Value="True">
                            <Setter Property="IsEnabled" Value="True"/>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>
    </StackPanel>
</Grid>

DataTrigger는 Binding 속성 값이 Value 와 같으면 내부의  Setter를 실행한다.
속성 값이 Value와 다르면 Style.Triggers  밖의 Setter를 실행한다.
Style.Triggers 외부에 Setter를 작성하지 않으면 기본값이다.

                            <DataTrigger Binding="{Binding IsRunning}" Value="True">
                                <Setter Property="IsEnabled" Value="False"/>
                            </DataTrigger>

Play 버튼은 IsRunning이 True일때 버튼의 IsEnabled는 Flalse이다.
Play 버튼은 IsRunning이 False일때 버튼의 IsEnabled는 True이다.

                            <DataTrigger Binding="{Binding IsRunning}" Value="True">
                                <Setter Property="IsEnabled" Value="True"/>
                            </DataTrigger>

Stop 버튼은 IsRunning이 True일때 버튼의 IsEnabled는 True이다.
Stop 버튼은 IsRunning이 False일때 버튼의 IsEnabled는 False이다.

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private bool isRunning = false;
    public bool IsRunning
    {
        get { return isRunning; }
        set
        {
            isRunning = value;
            OnPropertyChanged("IsRunning");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string name)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    private void Execute_Click(object sender, RoutedEventArgs e)
    {
        IsRunning = true;
    }

    private void Stop_Click(object sender, RoutedEventArgs e)
    {
        IsRunning = false;
    }
}

Play 버튼을 클릭하면 Execute_Click( ) 메쏘드가 실행된다.
Stop 버튼을 클릭하면 Stop_Click( ) 메쏘드가 실행된다.

다운로드 : BindingDemo_trigger.zip

 

콤보박스에서 색상 선택하기

콤보박스에서 칼라를 선택하면 옆의 텍스트에 표시한다.

콤보박스에서 칼라를 선택하면 바인딩 된  "Color"에 의해서 TextBlock은 문자열을 "Color" 색상으로 바꾼다.
소스는 INotifyPropertyChanged에 의해 바인딩 된 속성를 업데이트 하는 것밖에 없다.

<Window.Resources>
     <x:Array x:Key="ColorItems" Type="Color">
         <Color>Black</Color>
         <Color>Red</Color>
         <Color>Blue</Color>
         <Color>Yellow</Color>
         <Color>Green</Color>
     </x:Array>
 </Window.Resources>
 <Grid>
     <Grid.RowDefinitions>
         <RowDefinition Height="Auto"/>
     </Grid.RowDefinitions>
     <StackPanel Orientation="Horizontal">
         <ComboBox ItemsSource="{StaticResource ColorItems}"
                 SelectedValue="{Binding Color, UpdateSourceTrigger=PropertyChanged}"
                 Width="90" Height="23" Margin="5">
             <ComboBox.ItemTemplate>
                 <DataTemplate>
                     <Border Width="80" Height="20" Margin="5,0">
                         <Border.Background>
                             <SolidColorBrush Color="{Binding}"/>
                         </Border.Background>
                     </Border>
                 </DataTemplate>
             </ComboBox.ItemTemplate>
         </ComboBox>
         <TextBlock Text="Text" Height="23" Margin="5">
         <TextBlock.Foreground>
             <SolidColorBrush Color="{Binding Color}"/>
         </TextBlock.Foreground>
         </TextBlock>
     </StackPanel>
 </Grid>

 

using System.ComponentModel;

namespace BindingDemo
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private Color color = Colors.Black;
        public Color Color
        {
            get { return color; }
            set
            {
                color = value;
                OnPropertyChanged("Color");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string name)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

 

다운로드 : BindingDemo_ComboBox_Color.zip

 

DataGrid에서 칼라 선택

DataGrid에서 칼라를 선택하면  문자열을 해당 칼라로 업데이트 한다.

<Window x:Class="BindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BindingDemo"
        Title="BindingDemo" Height="224" Width="289" DataContext="{Binding}">
    <Window.Resources>
        <x:Array x:Key="ColorItems" Type="Color">
            <Color>Black</Color>
            <Color>Red</Color>
            <Color>Blue</Color>
            <Color>Yellow</Color>
            <Color>Green</Color>
        </x:Array>
        <x:Array x:Key="DataGridItems" Type="local:TestClass">
            <local:TestClass Color="Black" Text="AAA"/>
            <local:TestClass Color="Black" Text="BBB"/>
            <local:TestClass Color="Black" Text="CCC"/>
        </x:Array>
    </Window.Resources>
    <Grid>
        <DataGrid ItemsSource="{StaticResource DataGridItems}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridComboBoxColumn Header="색" ItemsSource="{StaticResource ColorItems}"
                                    SelectedValueBinding="{Binding Color, UpdateSourceTrigger=PropertyChanged}">
                    <DataGridComboBoxColumn.ElementStyle>
                        <Style TargetType="ComboBox">
                            <Setter Property="ItemTemplate">
                                <Setter.Value>
                                    <DataTemplate>
                                        <Border Width="80" Height="20" Margin="5,0">
                                            <Border.Background>
                                                <SolidColorBrush Color="{Binding}"/>
                                            </Border.Background>
                                        </Border>
                                    </DataTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </DataGridComboBoxColumn.ElementStyle>
                    <DataGridComboBoxColumn.EditingElementStyle>
                        <Style TargetType="ComboBox">
                            <Setter Property="ItemTemplate">
                                <Setter.Value>
                                    <DataTemplate>
                                        <Border Width="80" Height="20" Margin="5,0">
                                            <Border.Background>
                                                <SolidColorBrush Color="{Binding}"/>
                                            </Border.Background>
                                        </Border>
                                    </DataTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </DataGridComboBoxColumn.EditingElementStyle>
                </DataGridComboBoxColumn>
                <DataGridTextColumn Header="텍스트" Binding="{Binding Text}" IsReadOnly="True">
                    <DataGridTextColumn.ElementStyle>
                        <Style TargetType="TextBlock">
                            <Setter Property="Foreground">
                                <Setter.Value>
                                    <SolidColorBrush Color="{Binding Color}"/>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </DataGridTextColumn.ElementStyle>
                </DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

 

using System.ComponentModel;

namespace BindingDemo
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        private Color color = Colors.Black;
        public Color Color
        {
            get { return color; }
            set
            {
                color = value;
                OnPropertyChanged("Color");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string name)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }

    public class TestClass : INotifyPropertyChanged
    {
        private Color color = Colors.Black;
        public Color Color
        {
            get { return color; }
            set
            {
                color = value;
                OnPropertyChanged("Color");
            }
        }

        public string Text { get; set; }

        public TestClass()
        {
        }

        public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

        private void OnPropertyChanged(string name)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

다운로드 : BindingDemo_DataGrid_Color.zip

 

 

Canvas Scale

콤보박스에서 Canvas의 비율을 조정한다.
비율은 Canvas.RenderTransform의 ScaleTransoform으로 설정한다.
설정 값은 0.0 ~ 1.0 이다. 콤보박스는 % 값이므로 소스의 속성에서 %와 비율로 상호 변환한다.

<Window x:Class="BindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:BindingDemo"
        xmlns:s="clr-namespace:System;assembly=mscorlib"
        Title="BindingDemo" Height="380" Width="661" DataContext="{Binding}">
    <Window.Resources>
        <x:Array x:Key="ScaleItems" Type="s:Int32">
            <s:Int32>200</s:Int32>
            <s:Int32>100</s:Int32>
            <s:Int32>75</s:Int32>
            <s:Int32>50</s:Int32>
            <s:Int32>25</s:Int32>
        </x:Array>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ComboBox ItemsSource="{StaticResource ScaleItems}"
                SelectedValue="{Binding Scale, UpdateSourceTrigger=PropertyChanged}"
                Width="70" Height="23" Margin="5" HorizontalAlignment="Left"/>
        <Canvas Grid.Row="1">
            <Canvas.RenderTransform>
                <ScaleTransform ScaleX="{Binding CanvasScale}" ScaleY="{Binding CanvasScale}"/>
            </Canvas.RenderTransform>
            <Rectangle Canvas.Left="100" Canvas.Top="100" Width="100" Height="40" Fill="Red"/>
            <Ellipse Canvas.Left="200" Canvas.Top="30" Width="80" Height="80" Fill="Blue"/>
        </Canvas>
    </Grid>
</Window>

 

using System.ComponentModel;

namespace BindingDemo
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public int Scale
        {
            get { return (int)CanvasScale * 100; }
            set { CanvasScale = value / 100.0; }
        }

        private double canvasScale = 1.0;
        public double CanvasScale
        {
            get { return canvasScale; }
            set
            {
                if (value > 0)
                {
                    canvasScale = value;
                }
                OnPropertyChanged("CanvasScale");
            }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string name)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}

다운로드 : BindingDemo_Canvas_Scale.zip

 

참고 : http://cswpf.seesaa.net/index-9.html