<Window x:Class="WpfAddressBook.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" MinHeight="200" MinWidth="200" Title="MainWindow" Height="480" Width="640"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition Height="*"></RowDefinition> <RowDefinition Height="Auto"></RowDefinition> </Grid.RowDefinitions> <!--[1] 메뉴--> <Menu Grid.Row="0"> <MenuItem Header="파일(_F)" x:Name="mnuFile"> <Separator /> <MenuItem Name="miExit" Header="끝내기(_X)" </MenuItem> <MenuItem Header="도구(_T)" x:Name="mnuTool"> <MenuItem Header="백업" x:Name="miBackup"></MenuItem> </MenuItem> <MenuItem Header="도움말(_H)"> <MenuItem Header="주소록 정보(_O)" Name="miAbout"></MenuItem> </MenuItem> </Menu> <!--[2] 도구 모음--> <ToolBarTray Grid.Row="1"> <ToolBar> <StackPanel Orientation="Horizontal"> <Button x:Name="btnClose" Content="끝내기" /> </StackPanel> </ToolBar> </ToolBarTray> <!--[3] 주소록--> <Label Content="번호 : " Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="62,21,0,0" Name="lblNum" VerticalAlignment="Top" Width="120" /> <Label Content="이름 : " Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="62,55,0,0" Name="lblName" VerticalAlignment="Top" Width="120" /> <Label Content="휴대폰 : " Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="62,89,0,0" Name="lblMobile" VerticalAlignment="Top" Width="120" /> <Label Content="이메일 : " Grid.Row="2" Height="28" HorizontalAlignment="Left" Margin="62,123,0,0" Name="lblEmail" VerticalAlignment="Top" Width="120" /> <TextBox Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="188,26,0,0" Name="txtNum" VerticalAlignment="Top" Width="198" IsReadOnly="True" /> <TextBox Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="188,60,0,0" Name="txtName" VerticalAlignment="Top" Width="198" /> <TextBox Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="188,94,0,0" Name="txtMobile" VerticalAlignment="Top" Width="198" /> <TextBox Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="188,128,0,0" Name="txtEmail" VerticalAlignment="Top" Width="198" /> <Button Content="입력" Grid.Row="2" Height="23" HorizontalAlignment="Right" Margin="0,25,95,0" Name="btnAdd" VerticalAlignment="Top" Width="75" /> <Button Content="저장" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="448,60,0,0" Name="btnSave" VerticalAlignment="Top" Width="75" /> <Button Content="수정" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="448,94,0,0" Name="btnModify" VerticalAlignment="Top" Width="75" /> <Button Content="삭제" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="448,128,0,0" Name="btnDelete" VerticalAlignment="Top" Width="75" /> <Button Content="처음" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="111,167,0,0" Name="btnFirst" VerticalAlignment="Top" Width="75" /> <Button Content="이전" Height="23" HorizontalAlignment="Right" Margin="0,167,326,0" Name="btnPrev" VerticalAlignment="Top" Width="75" Grid.Row="2" /> <Button Content="다음" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="327,167,0,0" Name="btnNext" VerticalAlignment="Top" Width="75" /> <Button Content="마지막" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="434,167,0,0" Name="btnLast" VerticalAlignment="Top" Width="75" /> <DataGrid AutoGenerateColumns="True" Grid.Row="2" Height="114" HorizontalAlignment="Left" Margin="62,196,0,0" Name="dgvAddress" VerticalAlignment="Top" Width="461"> <DataGrid.Columns> <DataGridTextColumn Header="번호" Binding="{Binding Path=Num}"></DataGridTextColumn> </DataGrid.Columns> </DataGrid> <TextBox Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="67,327,0,0" Name="txtGo" VerticalAlignment="Top" Width="70" /> <Button Content="이동" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="154,327,0,0" Name="btnGo" VerticalAlignment="Top" Width="75" /> <Button Content=검색" Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="448,327,0,0" Name="btnSearch" VerticalAlignment="Top" Width="75" /> <TextBox Grid.Row="2" Height="23" HorizontalAlignment="Left" Margin="291,327,0,0" Name="txtSearch" VerticalAlignment="Top" Width="120" /> <!--[4] 상태바--> <StatusBar Grid.Row="3"> <Label Name="sslCount" Content="총 레코드 수 : "></Label> </StatusBar> </Grid> </Window> |
2. AddressBook.CS 클래스 파일 추가
using System; namespace WpfAddressBook { public class Address { public int Num { get; set; } public string Name { get; set; } public string Mobile { get; set; } public string Email { get; set; } } } |
3. F7 눌러 코드 비하인드 페이지 각각의 이벤트 작성
- [1] Private Member Variables #region Private Member Variables // 필드 선언부 : 주소록 정보 저장 private List<Address> addr = new List<Address>(); private string dir = System.IO.Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "MyAddress.txt"); private int currentIndex = 0; private bool blnModified = false; #endregion #region Constructors public MainWindow() { InitializeComponent(); this.Loaded += new RoutedEventHandler(MainWindow_Loaded); miExit.Click += new RoutedEventHandler(miExit_Click); miBackup.Click += new RoutedEventHandler(miBackup_Click); miAbout.Click += new RoutedEventHandler(miAbout_Click); txtName.TextChanged += new TextChangedEventHandler(txtModify_TextChanged); txtMobile.TextChanged += new TextChangedEventHandler(txtModify_TextChanged); txtEmail.TextChanged += new TextChangedEventHandler(txtModify_TextChanged); btnAdd.Click += new RoutedEventHandler(btnAdd_Click); btnSave.Click += new RoutedEventHandler(btnSave_Click); btnModify.Click += new RoutedEventHandler(btnModify_Click); btnDelete.Click += new RoutedEventHandler(btnDelete_Click); btnFirst.Click += new RoutedEventHandler(btnMove_Click); btnPrev.Click += new RoutedEventHandler(btnMove_Click); btnNext.Click += new RoutedEventHandler(btnMove_Click); btnLast.Click += new RoutedEventHandler(btnMove_Click); btnGo.Click += new RoutedEventHandler(btnGo_Click); btnSearch.Click += new RoutedEventHandler(btnSearch_Click); dgvAddress.SelectedCellsChanged += new SelectedCellsChangedEventHandler } #endregion #region Event Handers // DataGrid 셀 선택시 해당 레코드 텍스트 박스에 바인딩 void dgvAddress_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e) { if (dgvAddress.SelectedIndex != -1) { ShowRecord(dgvAddress.SelectedIndex); // 현재 선택된 인덱스 보이기 } } // 검색 void btnSearch_Click(object sender, RoutedEventArgs e) { DisplayData(txtSearch.Text); } // 이동 void btnGo_Click(object sender, RoutedEventArgs e) { if (txtGo.Text != "" && Convert.ToInt32(txtGo.Text) > 0 && Convert.ToInt32(txtGo.Text) <= addr.Count) { ShowRecord(Convert.ToInt32(txtGo.Text) - 1); } } // 처음 이전 다음 마지막 각각의 이벤트 핸들러 작성 void btnMove_Click(object sender, RoutedEventArgs e) { Button btn = sender as Button; if (btn.Name == "btnFirst") { if (currentIndex > 0) { currentIndex = 0; // 0번째 인덱스로 표시 } } else if (btn.Name == "btnPrev") { if (currentIndex > 0) { currentIndex--; } } else if (btn.Name == "btnNext") { if (currentIndex < addr.Count - 1) { currentIndex++; } } else if (btn.Name == "btnLast") { if (currentIndex != -1) { currentIndex = addr.Count - 1; } } ShowRecord(currentIndex); // 다시 데이터 표시 (다시 로딩) } // 삭제 void btnDelete_Click(object sender, RoutedEventArgs e) { if (txtNum.Text != "" && currentIndex != -1) { if (MessageBox.Show("정말 삭제 하시겠습니까?", "삭제", { addr.RemoveAt(currentIndex); MessageBox.Show("삭제 완료"); DisplayData(); } } } // 수정 void btnModify_Click(object sender, RoutedEventArgs e) { if (currentIndex != -1 && blnModified == true) { // 변경된 데이터로 addr 개체 인덱스 데이터 변경 addr[currentIndex].Name = txtName.Text; addr[currentIndex].Mobile = txtMobile.Text; addr[currentIndex].Email = txtEmail.Text; MessageBox.Show("수정 되었습니다", "수정 완료"); DisplayData(); blnModified = false; // 다시 초기화 } } // 저장 void btnSave_Click(object sender, RoutedEventArgs e) { if (addr.Count > 0) { SaveData(); } } // 입력, 추가 버튼 이벤트 핸들러 작성 void btnAdd_Click(object sender, RoutedEventArgs e) { if (btnAdd.Content.ToString() == "입력") { Address a = new Address(); a.Num = addr.Count + 1; // a.Name = txtName.Text.Trim(); a.Mobile = txtMobile.Text.Trim(); a.Email = txtEmail.Text.Trim(); addr.Add(a); DisplayData(); // 출력 } else { btnAdd.Content = "입력"; } ClearTextBox(); } // 3개의 텍스트 박스에서 공통으로 사용하는 이벤트 처리기 void txtModify_TextChanged(object sender, TextChangedEventArgs e) { if (txtNum.Text != "") // 데이터 로드된 상태에서만... { blnModified = true; // 변경 되었다 TRUE... } } // 폼 로드 void MainWindow_Loaded(object sender, RoutedEventArgs e) { if (File.Exists(dir)) { LoadData(); } this.sslCount.Content = "총 레코드 수 : " + addr.Count.ToString(); if (addr.Count > 0) { ShowRecord(0); // 첫번째 데이터 표시 btnAdd.Content = "추가"; } } // 정보 메뉴 void miAbout_Click(object sender, RoutedEventArgs e) { FrmAbout fa = new FrmAbout(); fa.ShowDialog(); } // 백업 메뉴 void miBackup_Click(object sender, RoutedEventArgs e) { string name = System.IO.Path.GetFileNameWithoutExtension(dir); string ext = System.IO.Path.GetExtension(dir).Replace(".", ""); // MyAddress20100101.txt로 저장 가능 하도록 System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, String.Format("{0}{1}.{2}" , name , String.Format("{0}{1:0#}{2}" , DateTime.Now.Year , DateTime.Now.Month , DateTime.Now.Day.ToString().PadLeft(2, '0') ) , ext ) ); if (File.Exists(dir)) { File.Copy(dir, newDir, true); //원본을 복사에서 백업 } // 끝내기 메뉴 void miExit_Click(object sender, RoutedEventArgs e) { // Windows Forms // Application.Exit(); // WPF Application.Current.Shutdown(); // 프로그램 종료 } #endregion #region Public Methods /// <summary> /// DB/File로 부터 데이터 읽어와 List에 저장 public void LoadData() { StreamReader sr = new StreamReader(dir, Encoding.Default); while (sr.Peek() >= 0) // -1 : 더 이상 읽을 데이터가 없을 때 { string[] arr = sr.ReadLine().Trim().Split(','); if (arr[0] != "" && arr[0] != null) { Address a = new Address(); a.Num = Convert.ToInt32(arr[0]); // 번호 인덱스 + 1 a.Name = arr[1]; a.Mobile = arr[2]; a.Email = arr[3]; addr.Add(a); } } sr.Close(); // sr.Dispose(); // DisplayData(); } /// <summary> /// List<T>에 자료를 다시 DB/File로 영구 저장 /// </summary> public void SaveData() { // 레코드에 엔터 구분, 필드는 콤마 구분으로 저장 StringBuilder sb = new StringBuilder(); int index = 0; foreach (Address a in addr) { sb.AppendLine(String.Format("{0},{1},{2},{3}" , ++index, a.Name, a.Mobile, a.Email)); } StreamWriter sw = new StreamWriter(dir, false, Encoding.Default); sw.Write(sb.ToString()); sw.Close(); sw.Dispose(); // MessageBox.Show("저장 되었습니다"); } // 데이터 표시 : DataGrid에 현재 주소록 정보 List<Address>를 출력 { var q = (from a in addr select a).ToList(); this.dgvAddress.ItemsSource = q; } // 검색어를 넘겨서 필터링 public void DisplayData(string query) { var q = (from a in addr where a.Name == query || a.Mobile == query || a.Email == query select a).ToList(); this.dgvAddress.ItemsSource = q; } // 레코드 보이기 : 현재 선택 또는 현재 인덱스의 레코드를 텍스트 박스에 바인딩 public void ShowRecord(int index) { // 현재 선택된 인덱스 +1 텍스트 박스에 출력 this.txtNum.Text = (index + 1).ToString(); this.txtName.Text = addr[index].Name; this.txtMobile.Text = addr[index].Mobile; this.txtEmail.Text = addr[index].Email; btnAdd.Content = "추가"; txtGo.Text = txtNum.Text; // 현재 선택된 인덱스 값 출력 } // 텍스트 클리어 private void ClearTextBox() { txtName.Text = txtMobile.Text = txtEmail.Text = String.Empty; } #endregion |
'.Net Project > WPF' 카테고리의 다른 글
05. WPF Windows 바탕화면 변경하기 (0) | 2010.05.21 |
---|---|
04. WPF PatientReferrals (0) | 2010.05.21 |
03. WPF 웹 브라우저 실행하여 날짜값 출력 (0) | 2010.05.21 |
02. WPF HelloWorld 텍스트 박스 내용 메시지 박스에 출력 (0) | 2010.05.21 |
01. WPF 시작하기 (0) | 2010.05.21 |