본문 바로가기
C#/WPF

OneWay와 TwoWay

by Falto 2023. 3. 1.
<Window x:Class="IamNamespace.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"
        mc:Ignorable="d"
        Height="450" Width="450" Background="#999999">
    <Grid>
        <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Width, UpdateSourceTrigger=PropertyChanged}"/>
    </Grid>
</Window>

바인딩을 하면 Window의 Width를 줄여서 TextBox의 Text를 바꾸거나, 그 역이 가능하다.

TextBox에 1940을 입력한 모습
Window의 크기를 줄여서 136이 입력된 모습

그러나 일방향으로만 Binding이 되도록 만들고 싶을 수 있다.

<Window x:Class="IamNamespace.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"
        mc:Ignorable="d"
        Height="450" Width="450" Background="#999999">
    <Grid>
        <TextBox Text="{Binding RelativeSource={RelativeSource AncestorType=Window}, Path=Width, UpdateSourceTrigger=PropertyChanged,
            Mode=OneWay}"/>
    </Grid>
</Window>

Mode=OneWay를 추가하면, Window의 크기를 늘리거나 줄일 때만 TextBox의 값이 변한다. TextBox의 값을 수정한다고 Window의 Width가 변하진 않는다. 즉 Window -> TextBox 방향이다.

OneWay를 OneWayToSource로 바꾸면 OneWay의 역일방향이 된다. 즉 TextBox -> Window 방향이다. Source는 당연히 Window를 의미한다.

 

OneWayToSource - TextBox -> Window로 일방적인 바인딩이 가능하다. Window의 크기를 줄여도 TextBox의 값은 변하지 않는다.

 

'C# > WPF' 카테고리의 다른 글

Binding - UpdateSourceTrigger  (0) 2023.03.01
RelativeSource Binding  (0) 2023.03.01
DataContext Binding  (0) 2023.03.01
[C# WPF] Binding  (0) 2023.02.18
[C# WPF] super mario 63의 cheat를 구현해 보자.  (0) 2023.02.03

댓글