<UserControl xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"  xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"  x:Class="SilverLightCityGas.BMA_SD_005"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="552" Height="352" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Background="#FF797979">
    <Grid x:Name="LayoutRoot" Background="#FFA4A4A4" ShowGridLines="True">
        <StackPanel Margin="10,10,10,10">

            <TextBlock Text="DataGrid Demonstration" Margin="0,20,10,20"
            FontFamily="Verdana" FontSize="18" FontWeight="Bold"
            Foreground="#FF5C9AC9" />

            <TextBlock Text="DataGrid with autogenerated columns:"/>
            <data:DataGrid x:Name="dataGrid1"
            Height="140" Margin="0,5,0,10"
            AutoGenerateColumns="True" />

            <TextBlock Text="DataGrid with row details sections:"/>
            <data:DataGrid x:Name="dataGrid3"
            Height="140" Margin="0,5,0,10"
            RowDetailsVisibilityMode="VisibleWhenSelected" >
                <data:DataGrid.RowDetailsTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock FontSize="12" Text="Address: " />
                            <TextBlock FontSize="12" Text="{Binding Address}"/>
                        </StackPanel>
                    </DataTemplate>
                </data:DataGrid.RowDetailsTemplate>
            </data:DataGrid>

            <TextBlock Text="DataGrid with configured columns:"/>
            <data:DataGrid x:Name="dataGrid4"
            Height="160" Margin="0,5,0,10"
            RowHeight="40" AutoGenerateColumns="False" >
                <data:DataGrid.Columns>
                    <data:DataGridTextColumn
                    Header="First Name"
                    Width="SizeToHeader"
                    Binding="{Binding FirstName}"
                    FontSize="20" />
                    <data:DataGridTextColumn
                    Header="Last Name"
                    Width="SizeToCells"
                    Binding="{Binding LastName}"
                    FontSize="20" />
                    <data:DataGridTextColumn
                    Header="Address"
                    Width="150"
                    Binding="{Binding Address}" >
                        <data:DataGridTextColumn.ElementStyle>
                            <Style TargetType="TextBlock">
                                <Setter Property="TextWrapping" Value="Wrap"/>
                            </Style>
                        </data:DataGridTextColumn.ElementStyle>
                        <data:DataGridTextColumn.EditingElementStyle>
                            <Style TargetType="TextBox">
                                <Setter Property="Foreground" Value="Blue"/>
                            </Style>
                        </data:DataGridTextColumn.EditingElementStyle>
                    </data:DataGridTextColumn>
                    <data:DataGridCheckBoxColumn
                    Header="New?"
                    Width="40"
                    Binding="{Binding IsNew}" />
                    <data:DataGridCheckBoxColumn
                    Header="Subscribed?"
                    Width="Auto"
                    Binding="{Binding IsSubscribed}"
                    IsThreeState="True" />
                </data:DataGrid.Columns>
            </data:DataGrid>

            <TextBlock Text="DataGrid with template column and custom alternating row backgrounds:"/>
            <data:DataGrid x:Name="dataGrid5"
            Height="125" Margin="0,5,0,10"
            AutoGenerateColumns="False"
            RowBackground="Azure"
            AlternatingRowBackground="LightSteelBlue">
                <data:DataGrid.Columns>
                    <!-- Name Column -->
                    <data:DataGridTemplateColumn Header="Name">
                        <data:DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Padding="5,0,5,0"
                                    Text="{Binding FirstName}"/>
                                    <TextBlock Text="{Binding LastName}"/>
                                </StackPanel>
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellTemplate>
                        <data:DataGridTemplateColumn.CellEditingTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBox Padding="5,0,5,0"
                                    Text="{Binding FirstName}"/>
                                    <TextBox Text="{Binding LastName}"/>
                                </StackPanel>
                            </DataTemplate>
                        </data:DataGridTemplateColumn.CellEditingTemplate>
                    </data:DataGridTemplateColumn>
                    <!-- Address Column -->
                    <data:DataGridTextColumn
                    Header="Address" Width="300"
                    Binding="{Binding Address}" />
                </data:DataGrid.Columns>
            </data:DataGrid>
        </StackPanel>

    </Grid>
</UserControl>

간단한 data grid 사용법

----------------------------------------------------------------------------------------------------------

바인딩 될 클래스

----------------------------------------------------------------------------------------------------------

namespace DataGridDetails_CS
{
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string State { get; set; }
        public string Zip { get; set; }
        public DateTime BirthDate { get; set; }
    }
}

----------------------------------------------------------------------------------------------------------

xaml 페이지

----------------------------------------------------------------------------------------------------------

<UserControl x:Class="DataGridDetails_CS.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:data="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data"
             xmlns:basics="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
    Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">

<data:DataGrid RowDetailsVisibilityMode="VisibleWhenSelected" x:Name="PeopleList" AutoGenerateColumns="False">

      * 가장기본적인 바인딩 클릭하면  RowDetailsTemplate 의 내용이 나타난다
<data:DataGrid.Columns>
                <data:DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" SortMemberPath="FirstName" />
                <data:DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" SortMemberPath="LastName" />
            </data:DataGrid.Columns>

* RowDetailsVisibilityMode 를 위한 템플릿

            <data:DataGrid.RowDetailsTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Vertical" Background="LightBlue">
                        <TextBlock FontWeight="Bold" Text="Address" />
                        <TextBox Text="{Binding Address}"/>                       
                        <TextBlock FontWeight="Bold" Text="City" />
                        <TextBox Text="{Binding City}" />
                        <TextBlock FontWeight="Bold" Text="Birth Date" />
                        <basics:DatePicker SelectedDate="{Binding BirthDate}" Text="{Binding BirthDate}" />
                    </StackPanel>
                </DataTemplate>
            </data:DataGrid.RowDetailsTemplate>
        </data:DataGrid>

    </Grid>
</UserControl>

----------------------------------------------------------------------------------------------------------

cs 페이지

----------------------------------------------------------------------------------------------------------

        void Page_Loaded(object sender, RoutedEventArgs e)
        {
            // clear any data context for the DataGrid
            PeopleList.ClearValue(DataContextProperty);

            /* The code below is sample data only.  This is done to
             * keep the sample small for you and as little configuration
             * as possible.  In the 'real world' this code would
             * likely retrieve data from your services (WCF, REST, ASMX, Astoria, etc)
             * and return the information for you to bind */
    List<Person> people = new List<Person>(); //위에서 만들었던  Person 개체를 List<> 형식으로 담습니다
            people.Add(new Person() { FirstName = "Tim", LastName = "Heuer", Address = "123 Main St", BirthDate = Convert.ToDateTime("9/18/1969"), City = "Queen Creek" });
            people.Add(new Person() { FirstName = "Scott", LastName = "Guthrie", Address = "1 Microsoft Way", BirthDate = Convert.ToDateTime("1/12/1969"), City = "Redmond" });
            people.Add(new Person() { FirstName = "Rob", LastName = "Bagby", Address = "456 S Central Ave", BirthDate = Convert.ToDateTime("9/18/1969"), City = "Phoenix" });
            people.Add(new Person() { FirstName = "Jesse", LastName = "Liberty", Address = "789 Blue St", BirthDate = Convert.ToDateTime("9/18/1969"), City = "Boston" });
            people.Add(new Person() { FirstName = "Dave", LastName = "Bost", Address = "1 Chicago Ave", BirthDate = Convert.ToDateTime("9/18/1969"), City = "Chicago" });
            people.Add(new Person() { FirstName = "Jason", LastName = "Mauer", Address = "1234 N 23rd Ave", BirthDate = Convert.ToDateTime("9/18/1969"), City = "Portland" });

            // bind the people to the DataGrid
PeopleList.ItemsSource = people; //생성한 데이터를 DataGrid 에 담습니다
        }

--------------------------------------------------------------------------------------------------------

참고사항

--------------------------------------------------------------------------------------------------------

AutoGenerateColumns="True" 사용해서 기본 컬렉션 사용하기

        <data:DataGrid
            Name="grdList"
            Margin="8,202,0,136"
            AutoGenerateColumns="True"
            ItemsSource="{Binding}" Width="244" d:LayoutOverrides="GridBox" HorizontalAlignment="Left" />

사용자 정의 템플릿

<data:DataGrid ItemsSource="{Binding}" x:Name="grdList" AutoGenerateColumns="False" Margin="120,96,112,64" DataContext="{Binding Mode=OneTime, Path=Publishing, Source={StaticResource BOOKDS}}" Style="{StaticResource DataGridStyle1}">

            <data:DataGrid.Columns>
                <!-- Name Column -->
                <data:DataGridTemplateColumn Header="Name">
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Vertical">
                                             <TextBlock Text="{Binding Title}"/>
                                             <TextBlock Text="{Binding PostID}"/>
                            </StackPanel>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
            </data:DataGrid.Columns>

        </data:DataGrid>

<data:DataGrid x:Name="dataGrid5"
    Height="125" Margin="0,5,0,10"
    AutoGenerateColumns="False"
    RowBackground="Azure"
    AlternatingRowBackground="LightSteelBlue">
    <data:DataGrid.Columns>
        <!-- Name Column -->
        <data:DataGridTemplateColumn Header="Name">
            <data:DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Padding="5,0,5,0"
                            Text="{Binding FirstName}"/>
                        <TextBlock Text="{Binding LastName}"/>
                    </StackPanel>
                </DataTemplate>
            </data:DataGridTemplateColumn.CellTemplate>
            <data:DataGridTemplateColumn.CellEditingTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBox Padding="5,0,5,0"
                            Text="{Binding FirstName}"/>
                        <TextBox Text="{Binding LastName}"/>
                    </StackPanel>
                </DataTemplate>
            </data:DataGridTemplateColumn.CellEditingTemplate>
        </data:DataGridTemplateColumn>             
        <!-- Address Column -->
        <data:DataGridTextColumn
            Header="Address" Width="300"
            Binding="{Binding Address}" />
    </data:DataGrid.Columns>
</data:DataGrid>

'WPF' 카테고리의 다른 글

태그삭제 Convert  (0) 2010.01.02
ObservableCollection&lt;(Of &lt;(T&gt;)&gt;) Class  (0) 2010.01.02
INotifyPropertyChanged  (0) 2010.01.02
Using Value Converters  (0) 2010.01.02
DataGrid 템플릿  (0) 2010.01.02
쿠키사용법  (0) 2009.12.15
웹 페이지에 Silverlight 추가  (0) 2009.12.15
간단하게 세션처럼 사용하기?!  (0) 2009.12.15
WCF 웹서비스를 이용한 데이터 바인딩  (0) 2009.12.15
ResizeGrip - Resizing (Mostly Custom) Windows  (0) 2009.12.15

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Browser;

namespace NewCitiZenBasic.TestViews
{
    public partial class TT : UserControl
    {
        public TT()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Making("memberNumber", "kojaedoo");
        }

        private void Making(string key, string value)
        {

//날짜입력설정
            //DateTime expiration = DateTime.Now.AddYears(100);     //현재 날자에 100년을 추가한 날자
            //string cookie = string.Format("{0}={1};expires={2}", key, value, expiration.ToString("R"));
            string cookie = string.Format("{0}={1};", key, value );
            HtmlPage.Document.SetProperty("Cookie", cookie);
        }

        private string GetCookie(string key)
        {
            string result = string.Empty;
            string[] cookies = HtmlPage.Document.Cookies.Split(';');

            foreach (string cookie in cookies)
            {
                string cookieStr = cookie.Trim();     //문자열 앞뒤로 공백 없애기
                if (cookieStr.StartsWith(key + "=", StringComparison.OrdinalIgnoreCase))  //Key= 과 같은
                {                                                                 //문자가 있을시 true 반환
                    string[] CrackedCookie = cookieStr.Split('=');
                    if (CrackedCookie[0] == key) {

                        result = CrackedCookie[1];
                    }
                }
            }
            return result;
        }

        private void btng_Click(object sender, System.Windows.RoutedEventArgs e)
        {
         // TODO: Add event handler implementation here.\
            MessageBox.Show(GetCookie("memberNumber"));
        }

    }
}

object 요소를 사용하면 지원되는 모든 브라우저와 호환되는 방식으로 HTML에 Silverlight 플러그 인을 포함하고 구성할 수 있습니다. 이 항목에서는 object 요소를 사용하여 다음과 같은 일반적인 작업을 수행하는 방법에 대해 설명합니다.

  • Silverlight 플러그 인을 포함하고 호스팅할 응용 프로그램을 지정합니다.

  • Silverlight가 설치되지 않은 경우 표시할 대체 HTML을 지정합니다.

이러한 작업은 HTML 페이지의 서로 다른 부분 및 특히 object 요소의 서로 다른 구성 매개 변수에 해당합니다. 다음 절차에서는 여러 작업을 독립적으로 설명하지만 이 항목의 끝부분에서는 전체 브라우저 간 HTML 예제를 빌드합니다.

각 절차의 조각을 사용하는 대신 최종 예제를 프로젝트의 템플릿으로 사용해야 합니다. 최종 예제는 브라우저 간 호환성을 확인하며 Visual Studio 및 Expression Blend가 테스트 페이지를 동적으로 생성하는 데 사용하는 템플릿을 기반으로 합니다.

HTML object 요소를 사용하여 추가 구성 작업을 수행할 수 있습니다. 자세한 내용은 Silverlight 플러그 인 개체 참조HTML 개체 요소의 속성 값을 참조하십시오. 참고 항목 단원에 나열된 항목은 특정 포함 시나리오의 추가 적용 범위를 제공합니다.

object 요소를 사용하는 대신 Silverlight.js 도우미 파일에서 제공하는 JavaScript 포함 함수를 사용합니다. 이러한 함수는 궁극적으로 object 요소를 생성하고 보다 편리하게 JavaScript를 개발하는 데 사용됩니다. 자세한 내용은 방법: JavaScript를 사용하여 웹 페이지에 Silverlight 추가를 참조하십시오.

Silverlight가 설치되지 않은 경우 표시할 대체 HTML을 지정하려면

<object id="SilverlightPlugin1" width="300" height="300"
    data="data:application/x-silverlight,"
    type="application/x-silverlight-2" >
    <param name="source" value="SilverlightApplication1.xap"/>

<!-- Display installation image. -->
    <a href="http://go.microsoft.com/fwlink/?LinkID=108182"
        style="text-decoration: none;">
        <img src="http://go.microsoft.com/fwlink/?LinkId=108181"
            alt="Get Microsoft Silverlight"
            style="border-style: none"/>
    </a>

</object>

방법: JavaScript를 사용하여 웹 페이지에 Silverlight 추가

Silverlight가 설치되지 않은 경우 표시할 대체 HTML을 지정하려면

<div id="silverlightControlHost">
    <script type="text/javascript">
        var getSilverlightMethodCall =
            "javascript:Silverlight.getSilverlight(\"2.0.30800.0\");"
        var installImageUrl =
            "http://go.microsoft.com/fwlink/?LinkId=108181";
        var imageAltText = "Get Microsoft Silverlight";
        var altHtml =
            "<a href='{1}' style='text-decoration: none;'>" +
            "<img src='{2}' alt='{3}' " +
            "style='border-style: none'/></a>";
        altHtml = altHtml.replace('{1}', getSilverlightMethodCall);
        altHtml = altHtml.replace('{2}', installImageUrl);
        altHtml = altHtml.replace('{3}', imageAltText);

      Silverlight.createObject(
            "ClientBin/SilverlightApplication1.xap",
            silverlightControlHost, "slPlugin",
            {
                width: "100%", height: "100%",
                background: "white", alt: altHtml,
                minRuntimeVersion: "2.0.30800.0"
            },
            { onError: onSLError, onLoad: onSLLoad },
            "param1=value1,param2=value2", "row3");
    </script>

예제 설명

다음 코드 예제에서는 Silverlight.js 파일을 사용하는 전체 HTML 페이지를 제공합니다. 여기에는 파란색 배경이 표시되며 표의 셀에 Silverlight 플러그 인 컨트롤이 네 개 포함되어 있습니다. 파란색 배경을 사용하면 기본 응용 프로그램 코드를 수정하지 않고 Visual Studio에서 이 예제를 테스트할 수 있습니다. 기본 사용자 인터페이스는 흰색 배경을 사용하여 호스트 웹 페이지의 파란색 배경과 다르게 표시됩니다.

이 예제에서는 다음과 같이 포함 함수를 사용하는 방법을 설명합니다.

  • 포함 함수의 반환 값을 사용하여 HTML 요소의 innerHTML 속성 설정. 예제의 window.onload 처리기를 참조하십시오.

  • 포함 함수를 다른 함수에 래핑하여 일반적인 구성 캡슐화. 예제의 embedSilverlight 함수를 참조하십시오.

  • 플러그 인을 호스팅하는 HTML 요소 내에서 직접 createObject 또는 createObjectEx 호출. 예제의 sl3Host 및 sl4Host 요소를 참조하십시오.

이 예제에는 여러 플러그 인 인스턴스가 포함되어 있으므로 Silverlight를 사용할 수 없을 때 그 중 하나의 인스턴스만 구성하여 설치 환경을 표시합니다. 기본 설치 환경을 방지하기 위해 첫 번째 인스턴스를 제외하고 모든 플러그 인 인스턴스에는 비어 있지 않은 alt 속성 값이 지정됩니다. 사용되는 alt 값은 아무 것도 표시되지 않도록 HTML 주석을 지정합니다.

이 예제에서 각 Silverlight 플러그 인에는 고유한 id 및 userContext 값이 지정됩니다. OnLoad 이벤트 처리기는 이러한 값을 사용하여 로드 순서를 나타내는 브라우저 상태 표시줄을 업데이트합니다.

이 예제에서는 JavaScript 함수를 사용하여 플러그 인의 OnError 이벤트를 처리하지만 구현은 빈 상태로 둡니다. Visual Studio에서 생성되는 기본 구현은 방법: HTML을 사용하여 웹 페이지에 Silverlight 추가를 참조하십시오. JavaScript 오류 처리기는 디버깅하는 동안에는 유용하지만 응용 프로그램을 배포할 때에는 일반적으로 제거합니다. JavaScript에서 처리할 수 있는 오류에 대한 자세한 내용은 오류 처리를 참조하십시오.

iframe 요소 및 기타 HTML 도움말 요소는 브라우저 간 호환성을 제공합니다. iframe을 지정하면 Safari 브라우저에서 페이지를 캐싱할 수 없습니다. Safari 캐싱을 사용하면 사용자가 이전에 방문한 Silverlight 페이지로 돌아갈 때 Silverlight 플러그 인이 다시 로드되지 않습니다. 자세한 내용은 Safari Developer FAQ를 참조하십시오.

코드

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<!-- saved from url=(0014)about:internet -->
<head>
    <title>EmbeddingWithJS</title>

    <style type="text/css">
    html, body {
        height: 100%;
        overflow: auto;
    }
    body {
        background: blue;
        padding: 0;
        margin: 0;
    }
    </style>
    <script type="text/javascript" src="Silverlight.js"></script>
    <script type="text/javascript">
        window.onload = function() {
            sl1Host.innerHTML = embedSilverlight(null, "sl1", "row1");
        }

        function embedSilverlight(parentElement, pluginId, userContext) {
            var altHtml = pluginId == "sl1" ? null : "<!--not installed-->";
            return Silverlight.createObject("ClientBin/EmbeddingWithJS.xap",
                parentElement, pluginId,
                {
                    width: "200", height: "50",
                    background: "white", alt: altHtml,
                    minRuntimeVersion:"2.0.30908.0", autoUpgrade:true
                },
                { onError: onSLError, onLoad: onSLLoad },
                "param1=value1,param2=value2", userContext);
        }

        function onSLLoad(plugIn, userContext, sender) {
            window.status +=
                plugIn.id + " loaded into " + userContext + ". ";
        }

        function onSLError(sender, args) {
            // Display error message.
        }
    </script>
</head>

<body>

    <table>
        <tr>
            <td id="sl1Host"/>
        </tr>
        <tr>
            <td id="sl2Host">
                <script type="text/javascript">
                    embedSilverlight(sl2Host, "sl2", "row2");
                </script>
            </td>
        </tr>
        <tr>
            <td id="sl3Host">
                <script type="text/javascript">
                    Silverlight.createObject(
                        "ClientBin/EmbeddingWithJS.xap", sl3Host, "sl3",
                        {
                            width: "200", height: "50",
                            background: "white", alt: "<!--not installed-->",
                            minRuntimeVersion: "2.0.30908.0"
                        },
                        { onError: onSLError, onLoad: onSLLoad },
                        "param1=value1,param2=value2", "row3");
                </script>
            </td>
        </tr>
        <tr>
            <td id="sl4Host">
                <script type="text/javascript">
                    Silverlight.createObjectEx({
                        source: "ClientBin/EmbeddingWithJS.xap",
                        parentElement: sl4Host,
                        id: "sl4",
                        properties: {
                            width: "200",
                            height: "50",
                            background: "white",
                            alt: "<!--not installed-->",
                            minRuntimeVersion: "2.0.30908.0" },
                        events: {
                            onError: onSLError,
                            onLoad: onSLLoad },
                        initParams: "param1=value1,param2=value2",
                        context: "row4"
                    });
                </script>
            </td>
        </tr>
    </table>
    <iframe style='visibility:hidden;height:0;width:0;border:0px'></iframe>
</body>
</html>

'WPF' 카테고리의 다른 글

INotifyPropertyChanged  (0) 2010.01.02
Using Value Converters  (0) 2010.01.02
DataGrid 템플릿  (0) 2010.01.02
간단한 data grid 사용법  (0) 2010.01.02
쿠키사용법  (0) 2009.12.15
간단하게 세션처럼 사용하기?!  (0) 2009.12.15
WCF 웹서비스를 이용한 데이터 바인딩  (0) 2009.12.15
ResizeGrip - Resizing (Mostly Custom) Windows  (0) 2009.12.15
SplashScreen 만들기  (0) 2009.12.15
초간단 실버라이트 웹서비스 사용하기  (0) 2009.06.30

using System;
using System.Collections.Generic;
namespace SessionDemo
{
public static class SessionManager
    {
private static Dictionary<string, object> session = new Dictionary<string, object>();
public static Dictionary<string, object> Session
        {
get { return SessionManager.session; }
set { SessionManager.session = value; }
        }
    }
}
SETTING :
SessionManager.Session["uname"] = "kunal";
GETTING :
txbUname.Text = SessionManager.Session["uname"].ToString();

'WPF' 카테고리의 다른 글

Using Value Converters  (0) 2010.01.02
DataGrid 템플릿  (0) 2010.01.02
간단한 data grid 사용법  (0) 2010.01.02
쿠키사용법  (0) 2009.12.15
웹 페이지에 Silverlight 추가  (0) 2009.12.15
WCF 웹서비스를 이용한 데이터 바인딩  (0) 2009.12.15
ResizeGrip - Resizing (Mostly Custom) Windows  (0) 2009.12.15
SplashScreen 만들기  (0) 2009.12.15
초간단 실버라이트 웹서비스 사용하기  (0) 2009.06.30
컨테이너(Container)  (0) 2009.06.03

1 웹콘피그 설정

wsHttpBinding 를  basicHttpBinding 변경

   <service behaviorConfiguration="TESTSliverlight.Web.Service1Behavior"
    name="TESTSliverlight.Web.Service1">

    <endpoint address="" binding="basicHttpBinding" contract="TESTSliverlight.Web.IService1">
      <!--
      <endpoint address="" binding="wsHttpBinding" contract="TESTSliverlight.Web.IService1">
      -->
     <identity>
      <dns value="localhost" />
     </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
   </service>
  </services>
</system.serviceModel>

2. wcf 웹서비스로 전달할 클래스 만들기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.Runtime.Serialization;
namespace TESTSliverlight.Web
{
    [DataContract]
    public class WCFBook
    {
        public WCFBook(string BookTitle) {

            this.BookTitle = BookTitle;
        }
        [DataMember]
        public string BookTitle { get; set; }

    }

}

3.웹서비스 만들기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace TESTSliverlight.Web
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config.
    public class Service1 : IService1
    {
        public void DoWork()
        {
        }

        public  List<WCFBook> GetBookData()
        {

         //하나의 값만 보내고 싶으면  return WCFBook 하면된다

        //실버라이트에서 받을땐 e.result.BookTitle 이런씩으로 받으면 됩니다

            List<WCFBook> li = new List<WCFBook>();
            li.Add(new WCFBook("1111"));
            li.Add(new WCFBook("2222"));
            li.Add(new WCFBook("3333"));

            return li;
        }
    }
}

실버라이트에서 처리하기

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel.Channels;
using System.ServiceModel;
using System.Collections.ObjectModel;
namespace TESTSliverlight
{
    public partial class DataList : UserControl
    {
        ServiceBook.Service1Client sclient;
        EndpointAddress defaultAddress;
        public DataList()
        {
            InitializeComponent();
            Binding defaultBinding = new System.ServiceModel.BasicHttpBinding();
            defaultAddress = new System.ServiceModel.EndpointAddress("http://localhost:62711/Service1.svc");

            sclient = new TESTSliverlight.ServiceBook.Service1Client(defaultBinding, defaultAddress);
            sclient.GetBookDataCompleted += new EventHandler<TESTSliverlight.ServiceBook.GetBookDataCompletedEventArgs>(sclient_GetBookDataCompleted);
            sclient.GetBookDataAsync();
        }

        void sclient_GetBookDataCompleted(object sender, TESTSliverlight.ServiceBook.GetBookDataCompletedEventArgs e)
        {
                        this.ListWCF.ItemsSource = e.Result; //리스트 박스에 데이터 바인딩
        }

    }
}

-----------------------------------------------------------------------------------------------------------------------

<UserControl x:Class="TESTSliverlight.DataList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="440" Height="392" xmlns:TESTSliverlight="clr-namespace:TESTSliverlight"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             xmlns:SB="clr-namespace:TESTSliverlight.ServiceBook">
<UserControl.Resources>
  <SB:WCFBook x:Key="WCFBookDS" d:IsDataSource="True"/>
  <DataTemplate x:Key="BookTitleTemplate">
            <StackPanel Orientation="Horizontal">
   <TextBlock Text="{Binding Path=BookTitle}" />
            <TextBlock Text="{Binding Path=BookTitle}" />
            <TextBlock Text="{Binding Path=BookTitle}" />
                </StackPanel>
  </DataTemplate>
</UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
     <TextBlock Height="48" HorizontalAlignment="Left" Margin="8,8,0,0" VerticalAlignment="Top" Width="192" Text="DATA LIST" TextWrapping="Wrap"/>
     <ListBox  Name="ListWCF" Margin="64,96,184,120" DataContext="{StaticResource WCFBookDS}"
                  ItemsSource="{Binding WCFBook}" ItemTemplate="{StaticResource BookTitleTemplate}"/>

    </Grid>
</UserControl>

'WPF' 카테고리의 다른 글

DataGrid 템플릿  (0) 2010.01.02
간단한 data grid 사용법  (0) 2010.01.02
쿠키사용법  (0) 2009.12.15
웹 페이지에 Silverlight 추가  (0) 2009.12.15
간단하게 세션처럼 사용하기?!  (0) 2009.12.15
ResizeGrip - Resizing (Mostly Custom) Windows  (0) 2009.12.15
SplashScreen 만들기  (0) 2009.12.15
초간단 실버라이트 웹서비스 사용하기  (0) 2009.06.30
컨테이너(Container)  (0) 2009.06.03
모듈화  (0) 2009.06.03

ResizeGrip - Resizing (Mostly Custom) Windows

ResizeGrip 클래스

업데이트: 2007년 11월

Window가 크기를 변경할 수 있도록 하는 Thumb 컨트롤의 구현을 나타냅니다.

ResizeGrip - Resizing (Mostly Custom) Windows

August 18th, 2008     |     9 Comments

In my most recent article, I write about how you can easily create a custom window. Custom windows are interesting because, for better or for worse, you get to override the default OS titlebar, minimize/maximize/close buttons, and related functionality. in favor of your own custom implementation:

The benefit is obvious. You can really set your application apart by providing your own window design. The downside is that you have to re-create all of the window functionality yourself. Things like dragging a window, minimizing, maximizing, and closing are not free. They aren’t particularly hard either, and I provide the code snippets for them at the end of my article. What isn’t trivial, though, is being able to resize a window.

In this post, I will provide a cheap solution for the window resizing problem. In a future post, I will talk about how to resize using a non-cheap but arguably better solution.

The ResizeGrip Control
When you make your window transparent, resizing (one of the features you normally would take for granted) is no longer available:

To help with that, you have what is known as the ResizeGrip control:

The ResizeGrip control, by default, positions itself on the bottom-right corner of your application window. When you hover over it with your mouse, you will get the familiar resize handles that indicate you can click and drag to resize your application as necessary:

Because of its position and orientation, you will only be able to resize in a NW-SE (Northwest-Southeast) manner. At least, it is better than not being able to resize your application at all.

Using ResizeGrip
To use the ResizeGrip control, you can’t just drag and drop it into your window via the Asset Library using Expression Blend. Actually, you can, but it won’t do anything such as actually resizing your application when you click and drag it around. The way to add a ResizeGrip to your application is to select your Window in your Object Tree in Expression Blend:

After you have done that, take a look in the Common Properties category in your Properties Inspector. There should be a drop-down menu labeled ResizeMode. Click on it and select the CanResizeWithGrip item:

Once you have done that, you will see your ResizeGrip control appear on the bottom-right corner of your window. If you run your application, you will be able to resize your application by using the ResizeGrip control.

Why I Don’t Prefer the ResizeGrip Control
If you are in a rush and need to get something that enables resizing, the ResizeGrip is a great solution. My biggest problem with it is that it breaks the expectations your users would have when using your application. When you go with a custom window style to emulate a traditional window but fail to provide obvious functionality like 8-sided resizing, then you need to evaluate whether a custom design is worth the tradeoff. The answer may well be "Yes", so don’t feel that not having proper resizing automatically rules out having custom window styles.

In a future post, I will describe how to implement window resizing by writing some code. It will be a great example of the old phrase, "No pain, no gain!"

프로그램 시작하기 전에 보여주는 이미지(로고) 등을 표시해주는 방법입니다.

using System.Windows;
using System.Threading;
using System;

namespace HDI_WPF_SplashScreen_cs
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
  public Window1()
  {
   InitializeComponent();
  }

  private void btnDemo_Click(object sender, RoutedEventArgs e)
  {
   SplashScreen sp = new SplashScreen("splash.jpg"); //표시해줄 이미지
   sp.Show(false);
   Thread.Sleep(3000);
   sp.Close(new TimeSpan(0, 0, 3)); //천천히 닫히기
  }
}
}

 

SilverlightService.svc 추가 합니다

public string Test() {

     return "kojaedoo";
}

메소드 추가

 

ISilverlightService.cs 파일에도  같은 함수 추가

[OperationContract]
string Test();

 

이것으로 웹서비스는 준비 끗

 

실버라이트 Page.xaml

private void Test()
     {
         EndpointAddress defaultAddress;
         ServiceRef.SilverlightServiceClient sc;
         Binding defaultBinding = new System.ServiceModel.BasicHttpBinding();
         defaultAddress = new System.ServiceModel.EndpointAddress("http://localhost:56445/SilverlightService.svc");
         sc = new NewCitiZenBasic.ServiceRef.SilverlightServiceClient(defaultBinding, defaultAddress);
         sc.TestAsync();
         sc.TestCompleted += new EventHandler<NewCitiZenBasic.ServiceRef.TestCompletedEventArgs>(sc_TestCompleted);
     }

 

     void sc_TestCompleted(object sender, NewCitiZenBasic.ServiceRef.TestCompletedEventArgs e)
     {
         MessageBox.Show(e.Result);
     }
     #endregion

 

 

웹서비스 테스트에서는 특정포트를 설정해놓으면 테스트하기 편리합니다.

복합 응용 프로그램 라이브러리를 기반으로 응용 프로그램은 잠재적으로 많은 느슨하게 결합된 복합 모듈로 구성되어있습니다. They need to interact with the shell to contribute content and receive notifications based on user actions. 그들은 껍질과 상호 작용하는 내용을 기반으로 사용자의 동작에 기여하고 알림을받을 필요가있다. Because they are loosely coupled, they need a way to interact and communicate with one another to deliver the required business functionality. 왜냐하면 그들은 느슨하게 결합하는, 그들은 서로 상호 작용하고 필요한 비즈니스 기능을 제공하는 의사 소통 방법이 필요합니다.

To tie together these various modules, applications based on the Composite Application Library rely on a dependency injection container. 이러한 다양한 모듈을 함께 넥타이하려면, 응용 프로그램은 복합 애플 리케이션 라이브러리를 기반으로 의존성 주입 컨테이너에 의존하고있습니다. Dependency injection containers can reduce the dependency coupling between objects by providing the facility to instantiate instances of classes and manage their lifetime based on the configuration of the container. 의존성 주입 컨테이너 클래스의 인스턴스를 인스턴스하고 평생 관리하는 컨테이너의 구성에 따라 시설을 제공하여 개체 간의 종속성 커플링을 줄일 수있습니다. During the objects creation, the container injects any dependencies that the object has requested into it. 객체를 생성하는 동안 컨테이너 종속성을 해당 개체가 그것에 주사를 요청했습니다. If those dependencies have not yet been created, the container creates and injects them first. 이러한 종속성이 아직 만들어지지 않은 경우, 컨테이너를 생성하고 처음으로 그들을 주입했다. In some cases, the container itself is resolved as a dependency. 일부의 경우, 컨테이너 자체가 종속성으로 해결됩니다. For example, modules often get the container injected, so they can register their views and services with that container. 예를 들어, 자주 주입 컨테이너를 얻을, 모듈 그래서 그들은 자신의 견해와 서비스 컨테이너에 등록할 수있습니다.

There are several advantages of using a container: 거기에 컨테이너를 사용하는 몇 가지 장점이있습니다 :

  • A container removes the need for a component to have to locate its dependencies or manage their lifetimes. 컨테이너는 종속성을 찾을 수 또는 그들의 수명을 관리하는 구성 요소에 대한 필요성이 제거됩니다.
  • A container allows swapping the implementation of the dependencies without affecting the component. 한 컨테이너는 구성 요소에 영향을주지 않고 의존성의 구현 스와핑 수있습니다.
  • A container facilitates testability by allowing dependencies to be mocked. 한 컨테이너 의존성을 조롱 수 있도록함으로써 테스트 용이하게합니다.
  • A container increases maintainability by allowing new components to be easily added to the system. 컨테이너는 시스템에 새로운 구성 요소를 쉽게 추가할 수 있도록하여 유지력을 증가시킵니다.

 

 

응용 프로그램의 컨텍스트에서 복합 응용 프로그램을 도서관에, 거기에 컨테이너로 구체적인 이점도있습니다 : 기초

  • A container injects module dependencies into the module when it is loaded. 한 컨테이너는 모듈이 로드될 때 모듈에 종속성을 주입합니다.
  • A container is used for registering and resolving presenters and views. 컨테이너 등록 및 발표자 및 플레이를 해결하는 데 사용됩니다.
  • A container creates presenters and presentation models and injects the view. 컨테이너 발표자와 프레 젠 테이션 모델을 생성하고보기를 주입했다.
  • A container injects the composition services, such as the region manager and the event aggregator. 컨테이너 지역 매니저와 이벤트 어그리게이터를 조성 등 서비스, 주사.
  • A container is used for registering module-specific services, which are services that have module-specific functionality. 컨테이너는 특정 기능이 서비스 모듈 - - 특정 서비스, 모듈을 등록하는 데 사용됩니다.

 

 

다음 코드를 주입하는 방법을 작동을 보여줍니다. When the PositionModule 언제 PositionModule is created by the container, it is injected with the regionManager and the container. 컨테이너에 의해 생성되고, 그것은 regionManager와 컨테이너와 주입니다. In the RegisterViewsAndServices method, which is called from the module's Initialize method, when the module is loaded, various services, views, and presenters are registered. 어떤 모듈이 로드될모듈의 초기화 방법, 다양한 서비스, 플레이에서 호출하는 방법을 RegisterViewsAndServices, 발표자 및 등록되어있습니다.

public PositionModule(IUnityContainer container, IRegionManager regionManager)
{
    _container = container;
    _regionManagerService = regionManager;
}

public void Initialize()
{
    RegisterViewsAndServices();
    ...
}

protected void RegisterViewsAndServices()
{
    _container.RegisterType<IAccountPositionService, AccountPositionService>(new ContainerControlledLifetimeManager());
    _container.RegisterType<IPositionSummaryView, PositionSummaryView>();
    _container.RegisterType<IPositionSummaryPresentationModel, PositionSummaryPresentationModel>();
    ...
}

 

컨테이너를 사용하여

Containers are used for two primary purposes, namely registering and resolving. 컨테이너 두 가지 기본적인 목적, 즉 해결하기위한 등록 및 사용되고있다.

Registering 등록

Before you can inject dependencies into an object, the types of the dependencies need to be registered with the container. 전에 종속성을 주입할 수있는 개체로, 의존성의 유형은 컨테이너에 등록해야합니다. Registering a type involves passing the container an interface and a concrete type that implements that interface. 등록 유형 컨테이너 수있는 인터페이스와 그 인터페이스를 구현하는 구체적인 유형을 통과한다. There are primarily two means for registering types and objects: through code or through configuration. 그 종류와 개체를 등록은 주로 두 가지 의미 : 코드를 통해 또는 구성됩니다. The specific means vary from container to container. 특정 의미 컨테이너를 컨테이너에 이르기까지 다양합니다.

Typically, there are two ways of registering types and objects in the container through code: 일반적으로, 거기에 코드를 통해 컨테이너의 종류와 개체 등록의 두 가지 방법이있습니다 :

  • You can register a type or a mapping with the container. 당신은 형식이나 컨테이너와 매핑을 등록할 수있습니다. At the appropriate time, the container will build an instance of the type you specify. 적절한시기에, 컨테이너를 지정하는 유형의 인스턴스를 구축할 예정이다.
  • You can register an existing object in the container. 당신이 컨테이너에있는 기존 개체를 등록할 수있습니다. The container will return a reference to the existing object. 이 컨테이너는 기존의 개체에 대한 참조를 반환합니다.

 

 

C # EmployeeModule.cs

this.container.RegisterType <IEmployeesController, EmployeesController> (); 

앞의 코드 예제에서, 당신은 어떻게 EmployeesController the IEmployeesController 인터페이스는 첫 전술된 접근법을 사용해서 등록되는 것을 볼 수있습니다. For an example of entering configuration information through the Unity container, see Entering Configuration Information . the 통합 컨테이너를 통해 구성 정보를 입력하는 예를 들어, 입력 구성 정보를 참조하십시오.

Types registered with the container have a lifetime. 종류의 컨테이너로 등록 일생. This can be either singleton (a single instance for the container, so each time you resolve you get the same instance) or instance (each time you resolve you get a new instance). 이 중 하나씩 컨테이너 (단일 인스턴스를, 그래서 당신이) 동일한 인스턴스를 얻을 또는 예를 들어 당신이 새 인스턴스를 얻을 해결 (각 시간)를 해결 할 때마다 수있습니다. The lifetime can be specified at registration or through configuration. 수명을 등록 또는 구성을 통해 지정할 수있습니다. The default lifetime depends on the container implementation. 기본값은 평생 컨테이너 구현에 따라 달라집니다. For example, the Unity container registers services as instances by default. 예를 들어, 기본적으로 인스턴스로 통합 컨테이너에 등록 서비스를 제공합니다.

 

다음 코드 예제는 어디 EmployeesPresenter 컨테이너에 의해 해결되고있다 보여줍니다.

C# EmployeeModule.cs

EmployeesPresenter 발표자 = this.container.Resolve <EmployeesPresenter> (); 

 

The Employee s Presenter constructor contains the following dependencies, which are injected when it is resolved.

public EmployeesPresenter(IEmployeesView view, IEmployeesListPresenter listPresenter, IEmployeesController employeeController)
    {
        this.View = view;
        this.listPresenter = listPresenter;
        this.listPresenter.EmployeeSelected += new EventHandler<DataEventArgs<BusinessEntities.Employee>>(this.OnEmployeeSelected);
        this.employeeController = employeeController;
        View.SetHeader(listPresenter.View);
    }

컨테이너를 사용하기위한 고려 사항

You should consider the following before using containers: 당신이 컨테이너를 사용하기 전에 다음 사항을 고려해야합니다 :

  • Consider whether it is appropriate to register and resolve components using the container: 등록 여부를 적절하고 해결 구성 요소는 컨테이너 사용을 고려 :
    • Consider whether the performance impact of registering in the container and resolving instances from it is acceptable in your scenario. 컨테이너에 등록 여부와 그것의 인스턴스를 해결의 성능에 미치는 영향을 고려하여 시나리오에서 사용할 수있습니다. For example, if you need to create 10,000 polygons to draw a surface within the local scope of a rendering method, the cost of resolving all of those polygon instances through the container might have a significant performance cost because of the container's use of reflection for creating each entity. 예를 들어, 만약 당신이 렌더링 방식의 지역 범위 내에서 표면 무승부로 10,000 다각형을 만들, 컨테이너를 통해 모든 이들 다각형 인스턴스의 해결의 비용 컨테이너의 성능 때문에 상당한 비용을 만들기위한 반성의 사용을 가지고있을 필요 각 엔티티.
    • If there are many or deep dependencies, the cost of creation can increase significantly. 많은 경우에는 또는 깊은 의존성, 창조의 비용을 크게 증가시킬 수있다.
    • If the component does not have any dependencies or is not a dependency for other types, it may not make sense to put it in the container. 어떤 의존성이없는 경우 또는 다른 유형의 구성 요소에 대한 종속성이없는 경우, 그것은 용기에 넣어 이해가되지 않을 수있습니다.
  • Consider whether a component's lifetime should be registered as a singleton or instance: 평생 a 싱글톤 여부 또는 구성 요소의 인스턴스로 등록해야한다 고려 :
    • If the component is a global service that acts as a resource manager for a single resource, such as a logging service, you may want to register it as a singleton. 하는 경우 구성 요소는 로깅 서비스와 같은 하나의 리소스에 대한 리소스 매니저의 역할을, 당신은 싱글톤으로 등록을 원하는 수있는 글로벌 서비스입니다.
    • If the component provides shared state to multiple consumers, you may want to register it as a singleton. 상태를 공유하는 경우에는 구성 요소가 여러 소비자에게 제공하고, 당신은 싱글톤으로 등록을 할 수있습니다.
    • If the object that is being injected needs to have a new instance of it injected each time a dependent object needs one, register it as a non-singleton. 만약 객체가 그것의 새 인스턴스가 필요 주입되고 각 시간 종속 개체, 하나의 요구가 아닌 - 싱글톤으로 등록을 주입했다. For example, each Presentation Model needs a new instance of a view. 예를 들어, 각 프레 젠 테이션 모델 뷰의 새 인스턴스가 필요합니다.
  • Consider whether you want to configure the container through code or configuration: 여부를 구성 컨테이너에 코드 또는 구성을 통해 원하는 고려 :
    • If you want to centrally manage all the different services, configure the container through configuration. 만일 중앙에서 구성을 통해 컨테이너를 구성하는 다른 모든 서비스를 관리하고자합니다.
    • If you want to conditionally register specific services, configure the container through code. 만약 당신이 조건부 코드를 통해 특정 서비스를 구성 컨테이너 등록 싶어요.
    • If you have module-level services, consider configuring the container through code so that those services are only registered if the module is loaded. 모듈 - 수준의 서비스를 받아야하는 경우, 코드를 통해 모듈이로드되는 경우에만 해당 서비스에 등록하고있는 컨테이너를 구성한다.

+ Recent posts