[Silverlight 예제 100선] Binding + Open API + LINQ 를 이용한 이미지 검색 APP
2010/01/05 14:53 / Silverlight/Tip & TechSilverlight 예제 100선
# Binding + Open API + LINQ 를 이용한 이미지 검색
# 프로젝트 만들기
검색 Application 을 만들기 위해 새 프로젝트를 생성 합니다. 상단 메뉴에서 파일-> 새로만들기 -> 프로젝트 -> Visual C# -> Silverlgiht 텝에서 Silverlight 응용프로그램 으로 프로젝트를 생성 합니다. 프로젝트 이름은 ImageSearch 라고 하겠습니다. ^^ 
# MainPage.xaml 수정 하기
이번에 만들 검색 App 의 화면은 간단합니다. 키워드가 들어간 TextBox 박스 한개와 , 리스트가 뿌려질 ListBox 1개 그리고 검색을 실행할 버튼 한개를 구성하여 App UI 만들도록 하겠습니다.
MainPage.xaml 페이지를 열어 아래와 같이 수정 합니다.
<UserControl x:Class="SearchApp.MainPage"
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" Width="600" Height="400">
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBox Width="450" HorizontalAlignment="Left" Grid.Row="0" Height="30" Margin="20,0,0,0" x:Name="KeyWord"/>
<Button Width="100" Height="30" HorizontalAlignment="Right" Margin="0,0,20,0" Content="Search" x:Name="SearchButton"/>
<ListBox Grid.Row="1" Margin="20" x:Name="ImageListBox">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Image Width="50" Height="50" HorizontalAlignment="Left" Source="{Binding ImageUrl}" Stretch="UniformToFill"/>
<HyperlinkButton Margin="60,0,20,0" Content="{Binding Title}" NavigateUri="{Binding LinkUrl}" VerticalAlignment="Center" TargetName="_Blank"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>

# LINQ 참조 추가하기
LINQ 는 기본적으로 시스템에 참조 되어 있지만 XML LINQ는 시스템 참조에 추가되어 있지 않습니다. 그래서 Xml Linq 를 직접 추가 해야 됩니다.



# MainPage.xaml.cs 수정하기
자!! 이제 본격적으로 Silverlight Application 을 코딩하기 시작 하겠습니다. 우선은 검색 App 에서 필요한 네임스페이스를 참조 합니다.
using System.Collections.ObjectModel; using System.Xml.Linq; using System.Windows.Browser;
이제 바인딩에 필요한 데이타를 만들기 위해 데이타 모델을 선언 합나다. 바인딩이 될 멤버는 꼭 Property 로 선언 되어야 합니다.
public class ImageData
{
public string ImageUrl { get; set; }
public string LinkUrl { get; set; }
public string Title { get; set; }
}
04 LinkUrl : 원본 이미지의 경로
05 Title : 제목
public partial class MainPage : UserControl
{
string apiKey = "API 키";
ObservableCollection imageList = new ObservableCollection();
public MainPage()
{
InitializeComponent();
Loaded += (object sender, RoutedEventArgs e) =>
{
ImageListBox.ItemsSource = imageList;
};
SearchButton.Click += (object sender, RoutedEventArgs e) =>
{
Search();
};
KeyWord.KeyUp += (object sender, KeyEventArgs e) =>
{
if (e.Key == Key.Enter)
{
Search();
}
};
}
void Search()
{
if (KeyWord.Text.Length <= 0)
{
MessageBox.Show("검색어를 입력하세요.");
KeyWord.Focus();
return;
}
WebClient wc = new WebClient();
wc.DownloadStringAsync(new Uri(string.Format("http://openapi.naver.com/search?key={0}&query={1}&target=image&start=1&display=100",apiKey,HttpUtility.UrlEncode(KeyWord.Text))));
wc.DownloadStringCompleted += (object sender, DownloadStringCompletedEventArgs e) =>
{
XDocument doc = XDocument.Parse(e.Result);
var xmlData = from data in doc.Descendants("item")
select new ImageData
{
ImageUrl = (string)data.Element("thumbnail"),
LinkUrl = (string)data.Element("link"),
Title = (string)data.Element("title")
};
imageList.Clear();
foreach (ImageData data in xmlData)
{
imageList.Add(data);
}
};
}
}
04 바인딩 에 찰떡 궁합인 ObservableCollection 객체인 imageList 를 선언 하였습니다.
08 Silverlight Application 이 로드 되었을때 바인딩 을 연결 합니다.
12 검색 버튼을 클릭했을때 검색을 시작합니다.
16 키워드 입력 박스에서 엔터 키 이벤트가 발생 되었을때 검색을 시작 합니다.
26 키워드 입력 박스에 아무것도 입력 되어 있지 않다면 경고를 발생 합니다.
33 OPEN API 데이타를 가져 오기 위해서 Webclient 를 선언 합니다.
35 DownloadStringAsync 를 이용해서 OPEN API 데이타를 요청 합니다.
36 요청한 데이타의 결과값을 가져 옵니다.
38 결과값을 XML 형식의 XDocument 객체로 파싱합니다.
39 LINQ 를 이용해서 데이타를 매칭 시킵니다.
47 기존의 검색 결과를 비웁니다.
48 검색 결과를 바인딩한 imageList 에 넣습니다.
# Silverlight Application 실행
디버그 -> 디버깅 시작을 눌러 Silverlight 프로젝트를 빌드하고 Silverlight Application 을 실행 합니다.


어때요 Binding + OPEN API + LINQ 를 이용한 Silverlight 활용법 찹 쉽죠잉~~~


