블로그 이미지
Magic_kit
study 관련자료를 한곳으로 자기 개발 목적으로 재태크 재무 관리 목적으로 일상생활의 팁을 공유 하기 위하여 블로그를 개설 하였습니다.

calendar

1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
반응형

Category

Recent Post

Recent Comment

Archive

2010. 5. 21. 02:37 .Net Project/WPF
반응형
1. 화면 UI 작성

<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)"
                          InputGestureText="Ctrl+X"></MenuItem>   

            </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

- [2] Constructors 

#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
            (dgvAddress_SelectedCellsChanged);

        }

#endregion

- [3] Event Handlers
 

#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("정말 삭제 하시겠습니까?", "삭제",
                                     MessageBoxButton.YesNo) == MessageBoxResult.Yes)

                {

 

                    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저장 가능 하도록
 
            string newDir =

                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

 

- [4] Public Methods  

#region Public Methods

        /// <summary>

        /// DB/File 부터 데이터 읽어와 List에 저장
        /// </summary>

        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> 출력
        public void DisplayData()

        {

            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 





반응형
posted by Magic_kit
2010. 5. 21. 02:02 .Net Project/WPF
반응형
1. 화면 UI 구성

<Window x:Class="WpfWallpagerWithIActiveDesktop.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">

    <Grid>

        <Button Name="btnChange" Content="바탕화면 변경" />

    </Grid>

</Window> 


2. F7 버튼 클릭 하여 코드 비하인드 페이지 작성
   (WPF API 사용하여 다음과 같이 작성하여 바탕화면을 변경하도록 하고 있습니다)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.Runtime.InteropServices;

 

namespace WpfWallpagerWithIActiveDesktop

{

    /// <summary>

    /// Interaction logic for MainWindow.xaml

    /// </summary>

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

 

            btnChange.Click += new RoutedEventHandler(btnChange_Click);

        }

 

        void btnChange_Click(object sender, RoutedEventArgs e)

        {

            int nResult ;

            nResult = WinAPI.SystemParametersInfo(20, 0, "C:\\Penguins.jpg", 0x1 | 0x2);

            MessageBox.Show("바탕화면 변경 되었습니다");

        }

    }

 

    public class WinAPI

    {

        [DllImport("user32.dll", CharSet=CharSet.Auto)]

        public static  extern int SystemParametersInfo
                (
int uAction , int uParam , string lpvParam , int fuWinIni) ;

    }

} 





반응형
posted by Magic_kit
2010. 5. 21. 01:54 .Net Project/WPF
반응형
1. 화면 UI 구성 - > Page 폴더 생성 ->
2. 위의 내용 .Xaml 파일을 추가  하도록 한다

3. 화면 디자인 구성
3 - 1 DescriptionPage

<Page x:Class="PatientReferrals.Pages.DescriptionPage"

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

      mc:Ignorable="d"

      d:DesignHeight="300" d:DesignWidth="300"

                  Title="Description" Width="400" WindowTitle="Referral Description">

    <Page.CommandBindings>

        <CommandBinding Command="Open" Executed="open_Executed" />

        <CommandBinding Command="Save" Executed="save_Executed" />

        <CommandBinding Command="NextPage"

            CanExecute="CommandBinding_CanExecute"  

            Executed="CommandBinding_Executed" />

    </Page.CommandBindings>

    <DockPanel Margin="5">

        <Menu DockPanel.Dock="Top">

            <MenuItem Header="File">

                <MenuItem Command="Open" Header="_Open" />

                <MenuItem Command="Save" Header="_Save" />

            </MenuItem>

            <MenuItem Header="Edit">

                <MenuItem Command="Cut" Header="_Cut" />

                <MenuItem Command="Copy" Header="C_opy" />

                <MenuItem Command="Paste" Header="_Paste" />

            </MenuItem>

        </Menu>

        <ToolBarTray DockPanel.Dock="Top">

            <ToolBar>

                <Button Command="Open" Content="Open" />

                <Button Command="Save" Content="Save" />

            </ToolBar>

            <ToolBar>

                <Button Command="Cut" Content="Cut" />

                <Button Command="Copy" Content="Copy" />

                <Button Command="Paste" Content="Paste" />

            </ToolBar>

        </ToolBarTray>

        <StackPanel>

            <TextBox x:Name="description" Height="300" SpellCheck.IsEnabled="True"

                TextWrapping="Wrap" VerticalAlignment="Top" />

            <Button x:Name="nextPage" Command="{x:Static NavigationCommands.NextPage}"

                Content="" HorizontalAlignment="Right" Margin="0,10,0,0" Width="60" />

        </StackPanel>

    </DockPanel>

</Page> 




3 - 2  DetailsPage

<Page x:Class="PatientReferrals.Pages.DetailsPage"

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

      mc:Ignorable="d"

      d:DesignHeight="300" d:DesignWidth="300"

                  Title="상세보기" Width="400" WindowTitle="Referral Details">

    <Page.CommandBindings>

        <CommandBinding Command="NextPage" CanExecute="CommandBinding_CanExecute"

            Executed="CommandBinding_Executed"></CommandBinding>   

    </Page.CommandBindings>

   

<StackPanel Margin="10">   

        <Grid>

            <Grid.ColumnDefinitions>

                <ColumnDefinition />

                <ColumnDefinition Width="Auto" />

            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>

                <RowDefinition />

                <RowDefinition />

                <RowDefinition />

                <RowDefinition />

                <RowDefinition />

                <RowDefinition />

                <RowDefinition />

                <RowDefinition />

            </Grid.RowDefinitions>

 

            <TextBlock FontWeight="Bold" Grid.Column="0" Grid.Row="0" Margin="0,10,0,0"

                Text="Patient Name:" />

            <TextBox x:Name="patientName" Grid.Column="0" Grid.Row="1" Margin="0,0,5,0" />

            <Button x:Name="patientSearch" Content="Search" Grid.Column="1" Grid.Row="1"

                Width="60" Click="patientSearch_Click" />           

            <TextBlock FontWeight="Bold" Grid.Column="0" Grid.Row="2" Margin="0,10,0,0"

                Text="Search Results:" />

            <ListBox x:Name="patientResults" Grid.Column="0" Grid.ColumnSpan="2"

                Grid.Row="3" MinHeight="50" />

 

            <TextBlock FontWeight="Bold"

                       Grid.Column="0"

                       Grid.Row="4"

                       Margin="0,10,0,0"

                       Text="Specialist Name:" />

            <TextBox x:Name="specialistName"

                     Grid.Column="0"

                     Grid.Row="5"

                     Margin="0,0,5,0" />

            <Button x:Name="specialistSearch"

                    Content="Search"

                    Grid.Column="1"

                    Grid.Row="5"

                    Width="60" Click="specialistSearch_Click" />

            <TextBlock FontWeight="Bold"

                       Grid.Column="0"

                       Grid.Row="6"

                       Margin="0,10,0,0"

                       Text="Search Results:" />

            <ListBox x:Name="specialistResults"

                     Grid.Column="0"

                     Grid.ColumnSpan="2"

                     Grid.Row="7"

                     MinHeight="50" /> 

        </Grid> 

        <Button x:Name="next" Command="NextPage" Content="다음" HorizontalAlignment="Right"

            Margin="0,10,0,0" Width="60" /> 

    </StackPanel>

</Page> 


3 - 3 Summary Page

<Page x:Class="PatientReferrals.Pages.SummaryPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Loaded="Page_Loaded"

    Title="Summary"

    WindowTitle="Referrals Summary"

    Width="400">

 

    <StackPanel Margin="5">

 

        <TextBlock Style="{DynamicResource label}"

                   Text="Patient Name:" />

        <Label x:Name="patientName"

               Margin="10, 0, 0, 0"

               Content="{Binding}" />

        <TextBlock Style="{DynamicResource label}" 

                   Text="Specialist Name:" />

        <Label x:Name="specialistName"

               Margin="10, 0, 0, 0"

               Content="{Binding}" />

        <TextBlock Style="{DynamicResource label}" 

                   Text="Description:" />

        <TextBlock x:Name="descripiton"

                   Margin="12, 0, 0, 0"

                   Text="{Binding}"

                   TextWrapping="Wrap" />

 

        <StackPanel HorizontalAlignment="Right"

                    Orientation="Horizontal">

            <Button x:Name="send"

                    Click="send_Click"

                    Content="Send"

                    Margin="0, 0, 5, 0"

                    Width="60" />

            <Button x:Name="cancel"

                    Click="cancel_Click"

                    Content="Cancel"

                    Width="60" />

        </StackPanel>       

    </StackPanel>

</Page> 


4. F7 번을 클릭하여 코드 비하인드 페이지 작성

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using System.IO; //

using Microsoft.Win32; //

 

namespace PatientReferrals.Pages

{

    public partial class DescriptionPage : Page

    {

        public DescriptionPage()

        {

            InitializeComponent();

        }

 

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) {

            e.CanExecute = (description.Text.Length > 0); // 입력된 내용이 존재 하면 활성화

        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {

            SummaryPage page = new SummaryPage(); // 아직 만들지 않음

            page.Description = description.Text; // 이번에는 속성 사용해 상태 확인

            NavigationService.Navigate(page); // 이동

        }

        // 텍스트 파일에 저장된 설명을 읽어서 텍스트 박스에 출력

        private void open_Executed(object sender, ExecutedRoutedEventArgs e) {

            OpenFileDialog dialog = new OpenFileDialog();

            if (dialog.ShowDialog().GetValueOrDefault()) {

                using (StreamReader reader = new StreamReader(dialog.FileName)) {

                    description.Text = reader.ReadToEnd();

                }

            }

        }

        // 변경된 설명을 파일로 저장

        private void save_Executed(object sender, ExecutedRoutedEventArgs e) {

            SaveFileDialog dialog = new SaveFileDialog();

            if (dialog.ShowDialog().GetValueOrDefault()) {

                using (StreamWriter writer = new StreamWriter(dialog.FileName)) {

                    writer.Write(description.Text);

                }

            }

        }

    }

} 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using Contoso.Data; //

 

namespace PatientReferrals.Pages

{

    /// <summary>

    /// Interaction logic for DetailsPage.xaml

    /// </summary>

    public partial class DetailsPage : Page

    {

        public DetailsPage()

        {

            InitializeComponent();

        }

 

        private void patientSearch_Click(object sender, RoutedEventArgs e)

        {

            List<Patient> patientList = new List<Patient>(Patient.Patients);

 

            string searchText = patientName.Text;

            List<Patient> matches = patientList.FindAll(

                p => p.FirstName.Contains(searchText) || p.LastName.Contains(searchText));

 

            patientResults.ItemsSource = matches;

        }

 

        private void specialistSearch_Click(object sender, RoutedEventArgs e)

        {

            List<Specialist> specialistList =

                            new List<Specialist>(Specialist.Specialists);

 

            string searchText = specialistName.Text;

            List<Specialist> matches = specialistList.FindAll(

                s => s.Name.Contains(searchText));

 

            specialistResults.ItemsSource = matches;

        }

 

        // 해당 컨트롤에 대해서 활성화 여부 결정´

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)

        {

            e.CanExecute =

                (patientResults.SelectedIndex >= 0 && specialistResults.SelectedIndex >= 0);

        }

        // 활성화된 컨트롤을 클릭 하였을때 실행되는 코드

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)

        {

            // 다음 페이지로 값을 넘기지 않으려면 상태값 보관             
            Application
.Current.Properties["PATIENT"] = patientResults.SelectedValue;

            Application.Current.Properties["SPECIALIST"] = specialistResults.SelectedValue;

            // 다음 페이지로 이용

            NavigationService.Navigate(

                new Uri("Pages\\DescriptionPage.xaml", UriKind.Relative));

        }

    }

} 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

using Contoso.Data;

 

namespace PatientReferrals.Pages

{

    /// <summary>

    /// Interaction logic for SummaryPage.xaml

    /// </summary>

    public partial class SummaryPage : Page

    {

        public SummaryPage()

        {

            InitializeComponent();

        }

 

        private void Page_Loaded(object sender, RoutedEventArgs e)

        {

            // Populate the form with data.

            patientName.DataContext = Application.Current.Properties["PATIENT"];

            specialistName.DataContext = Application.Current.Properties["SPECIALIST"];

            descripiton.DataContext = this.Description;

        }

 

        private void send_Click(object sender, RoutedEventArgs e)

        {

            // Alert the user that the process is complete.

            MessageBox.Show("Patient information sent.", Title,

                MessageBoxButton.OK, MessageBoxImage.Information);

 

            RedirectToStart();

        }

 

        private void cancel_Click(object sender, RoutedEventArgs e)

        {

            RedirectToStart();

        }

 

        void RedirectToStart()

        {

            // Go back to the start page.

            // ...TODO

            // 다시 메인

            NavigationService.Navigate(

                new Uri("Pages\\DetailsPage.xaml", UriKind.Relative));

        }

 

        public string Description { get; set; }

    }

} 


반응형
posted by Magic_kit
2010. 5. 21. 01:29 .Net Project/WPF
반응형
1. 화면 UI 구성

<Page x:Class="WpfBrowserApplication.Page1"

      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

      mc:Ignorable="d"

      d:DesignHeight="300" d:DesignWidth="300"

      Title="Page1">

    <StackPanel>

        <Button x:Name="btnOK" Content="클릭하시오..." />

    </StackPanel>

</Page> 


2. F7 통한 코드 작성

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

 

namespace WpfBrowserApplication

{

    /// <summary>

    /// Interaction logic for Page1.xaml

    /// </summary>

    public partial class Page1 : Page

    {

        public Page1()

        {

            InitializeComponent();

 

            btnOK.Click += new RoutedEventHandler(btnOK_Click);

        }

 

        void btnOK_Click(object sender, RoutedEventArgs e)

        {

            MessageBox.Show(DateTime.Now.ToString());

        }

    }

} 


3. 결과 화면
 




반응형
posted by Magic_kit
prev 1 2 next