XAML Design Time Data Binding

김정환(John.Kim)
OldbeeDev
Published in
5 min readOct 23, 2017

Visual Studio에서 XAML 코딩을 하면 XAML 디자이너가 실시간으로 UI 렌더링을 해줘서 편리하다. 한가지 아쉬움이 있다면 XAML 디자이너는 Static한 XAML 코드만 렌더링하기 때문에 각 속성에 바인딩된 실제 값은 보여주지 않는다는 점이다. 하지만 MVVM Ligth Toolkit을 사용하면 이런 아쉬움을 해결할 수 있다.

MvvmLight 설치

먼저 “Manage NuGet Package” 메뉴를 통해 MvvmLight 레퍼런스를 프로젝트에 추가한다.

설치가 완료되면 ViewModelLocator, MainViewModel 등의 기본 코드가 프로젝트에 삽입된다.

샘플 코드

<Window x:Class="WpfApp9.MainWindow"
... 중략 ...
DataContext="{Binding Path=Main, Source={StaticResource Locator}}">
<Grid Margin="8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0" ItemsSource="{Binding PoemList}" />
<TextBox Grid.Column="1" Text="{Binding Poem}"/>
</Grid>
</Window>

MainWindow의 DataContext에 바인딩된 Main 변수는 MainViewModel 타입이다.

public class MainViewModel : ViewModelBase
{
public string Poem
{
get { return _poem; }
set { _poem = value; RaisePropertyChanged(); }
}
private string _poem;
public List<string> PoemList
{
get { return _poemList; }
set { _poemList = value; RaisePropertyChanged(); }
}
private List<string> _poemList;
}

MvvmLight을 사용하면 모든 ViewModel 클래스는 ViewModelBase는 상속받고 set 메소드에서 RaisePropertyChanaged()를 호출해준다.

Design-Time 데이터 입력하기

MainViewModel에 기본 생성자를 추가하고 아래와 같은 코드를 입력한다.

public MainViewModel()
{
if (IsInDesignMode)
{
PoemList = new List<string> {
"단편시1", "단편시2", "단편시3", "단편시4", "단편시5"
};
Poem = "너인줄\n알았는데\n\n너라면 좋았을걸" +
"\n\n\n\n\n\n- " +
"'금요일 같은데 목요일' 중에서 -";
}
}

빌드만 다시 해서 XAML 디자이너로 MainWindow.xaml을 확인해보면 아래와 같이 바인딩된 값이 화면에 표시되는 것을 볼 수 있다.

하상욱 단편집 발췌

if (IsInDesignMode) { } 내부는 XAML 디자이너가 렌더링할 때만 수행되는 특별한 영역이다.

public class DemoViewModel : ViewModelBase
{
public void DoSomething()
{
if (IsInDesignMode)
{
// This code runs in the visual designer and Blend
}
}
}

만약 ViewModelBase가 아닌 클래스에서 Design Time Data Binding을 하려면 IsInDesignModeStatic 속성을 사용한다.

public class NotViewModel
{
public void DoSomethingElse()
{
if (ViewModelBase.IsInDesignModeStatic)
{
// This code runs in the visual designer and Blend
}
}
}

바인딩된 Property 값을 변경한 후에는 빌드를 다시 해야 XAML 디자이너에 반영된다.

Wrapup :

MvvmLight 좋아요. 😉

References :

https://msdn.microsoft.com/en-us/magazine/dn169081.aspx

--

--