CollectionViewSource

CollectionViewSource을를는 CollectionView 클래스 또는 CollectionView에서 파생된 클래스에 대한 프록시입니다.CollectionViewSource는 XAML 코드에서를 이러한 설정을 기본 보기로 전달하는 일반적으로 사용되는 CollectionView 속성을 설정할 수 있습니다. CollectionViewSource에는 실제 보기를 보유하는 View 속성 및 원본 컬렉션을 보유하는 Source 속성이 있습니다.

컬렉션 뷰는 기본 소스 컬렉션 자체를 조작할 필요 없이 정렬, 필터 및 그룹화 쿼리를 기반으로 컬렉션을 탐색하고 표시하는 데 사용할 수 있는 바인딩 소스 컬렉션의 최상위 계층으로 간주할 수 있습니다.INotifyCollectionChanged 인터페이스가 소스 컬렉션에서 구현될 경우 CollectionChanged 이벤트에서 발생되는 변경 내용은 뷰로 전파됩니다.

뷰는 기본 소스 컬렉션을 변경하지 않으므로 각 소스 컬렉션에 여러 개의 뷰를 연결하여 사용할 수 있습니다.예를 들어 Task 개체의 컬렉션을 사용할 수 있습니다.또한 뷰를 사용하면 동일한 데이터를 여러 가지 다른 방식으로 표시할 수 있습니다.예를 들어 페이지 왼쪽에 우선 순위별로 정렬된 작업을 표시하고 오른쪽에 영역별로 그룹화된 작업을 표시할 수 있습니다.

자세한 내용은 데이터 바인딩 개요에서 컬렉션에 바인딩 단원을 참조하십시오.

한마디로 상태변경이 일어나면 그 상태를 알려준다.

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=KO-KR&k=k(SYSTEM.WINDOWS.DATA.COLLECTIONVIEWSOURCE);k(COLLECTIONVIEWSOURCE);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22);k(DevLang-CSHARP)&rd=true

사용했을때와 안했을때 차이점

 

image

위와  같은 화면을 구현 할 꺼다

DataGrid 에서 행을 선택하면 아래하단에 데이터가 자동으로 바인딩된다.

 

데이터 개체 만들기

image


비주얼스튜디오2010 에서 툴을 이용해서 만들면?

image

image

아까 위에서 만든 개체 선택

image

이렇게 나타난다.

위에서 만들어진 데이터 소스를 끌어주면 끝!

소스를 보면 리소스가 추가되었고

CollectionViewSource 형식으로 만들어져 있다.

image

그리드 데이터 컨텍스트에서 받는다

image

image

비하인드 코드 처리

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //가짜 데이터 만들기
            List<Customer> list = new List<Customer>();
            list.Add(new Customer { Age = 19, Name = "kojaedoo" });
            list.Add(new Customer { Age = 129, Name = "kojaedoo1" });
            list.Add(new Customer { Age = 49, Name = "kojaedoo2" });
            list.Add(new Customer { Age = 59, Name = "kojaedoo3" });
            list.Add(new Customer { Age = 69, Name = "kojaedoo4" });
            list.Add(new Customer { Age = 89, Name = "kojaedoo5" });



            //비주얼스트디오에서 자동으로 만들어준 코드 입니다.
            System.Windows.Data.CollectionViewSource customerViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("customerViewSource")));
            // CollectionViewSource.Source 속성을 설정하여 데이터를 로드합니다.
            customerViewSource.Source = list;                    
            
            
        }
끝!

수동(?)으로 할려면?

그리드에 있던 바인딩을 제거한다.

image

CollectionViewSource 만들어서 끼워주고 cv 를 바인딩합니다.

image

아까 그리드에다가 바인딩 해 주면된다.

 

만약 CollectionViewSource 사용하지 않는다면?

image

image

나이 49/ kojaedoo2 를 선택해도 아래의 컨트롤에는 반영이 되질 않는다.

정상적이라면 아래 박스에는 kojaedoo2 와 49가 바인딩 되어야한다.

 

Focus 를 얻으면 텍스트박스 테두리를 변경해보자

image

위의 화면은 실제 구현된 모습, 입력을 하려고 컨트롤에 커서가 가면 테두리 색깔이 변경된다

템플릿 수정화면으로 들어간다.

image

일단 색깔변경 스토리 보드를 하나 만들자 난 색깔만 변경 ㅋ

image

 

image

 

이제 포커스 받았을 때 스토리 보드 실행 만 하면 됨

 

Triggers 작업화면으로 이동

image

이벤트 클릭

포커스를 받으면 스토리보드 실행 LostFocus 일땐 스토리 보드 Remove 이러면 끗~

image

 

image

처음 실행될때는 스토리보드를 Remove 시켰다 컨트롤이 로드 될 때 포커스를 받나보다 ㅋ

image

 

F5 ㄱㄱ

간단한 컨텍스트 바인딩 하기

드롭다운 개체에 의해서 하위 컨트롤의 데이터 값이 변경됩니다.

image

 

image

 

데이터로 사용된 개체

    public class Customer
    {
        public string Name { get; set; }
        public List<Order> Orders { get; set; }

        public override string ToString()
        {
            return this.Name;
        }
        
        public static List<Customer> CreateCustomers()
        {
            return new List<Customer>
            {
                new Customer 
                {
                    Name="Customer 1",
                    Orders=new List<Order>
                    {
                        new Order
                        {
                            Desc="Big Order",
                            OrderDetails=new List<OrderDetail>
                            {
                                new OrderDetail { Product="Glue", Quantity=21 },
                                new OrderDetail { Product="Fudge", Quantity=32 }
                            }
                        },
                        new Order
                        {
                            Desc="Little Order",
                            OrderDetails=new List<OrderDetail>
                            {
                                new OrderDetail { Product="Ham", Quantity=1 },
                                new OrderDetail { Product="Yarn", Quantity=2 }
                            }
                        }
                    }
                },
                new Customer 
                {
                    Name="Customer 2",
                    Orders=new List<Order>
                    {
                        new Order
                        {
                            Desc="First Order",
                            OrderDetails=new List<OrderDetail>
                            {
                                new OrderDetail { Product="Mousetrap", Quantity=4 }
                            }
                        }
                    }
                },
            };
        }
    }

 

MainWindow.xaml

<Window x:Class="TestWpfApplication.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>

        <ComboBox 
        IsSynchronizedWithCurrentItem="True" 
        ItemsSource="{Binding Path=.}" Margin="0,35,0,255" />
        <Label Content="{Binding Path=Name}" Height="34" HorizontalAlignment="Left" Margin="12,120,0,0" Name="label1" VerticalAlignment="Top" Width="195" />
        <ComboBox ItemsSource="{Binding Path=Orders}" Margin="12,189,296,101" />
        <Label Content="컨텍스트 개체" Height="28" HorizontalAlignment="Left" Margin="0,12,0,0" Name="label2" VerticalAlignment="Top" />
        <Label Content="현재의 컨텍스트 개체안에 (Name)항목" Height="28" HorizontalAlignment="Left" Margin="12,86,0,0" Name="label3" VerticalAlignment="Top" Width="195" />
        <Label Content="현재의 컨텍스트 개체안에 (Orders)항목리스트" Height="28" HorizontalAlignment="Left" Margin="12,160,0,0" Name="label4" VerticalAlignment="Top" Width="309" />
        <Label Content="드롭다운하면 현재의 개체에 맞게 아래데이터가 변경된다." Height="28" HorizontalAlignment="Left" Margin="0,52,0,0" Name="label5" VerticalAlignment="Top" />
    </Grid>
</Window>

MainWindow.xaml.cs

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.Diagnostics;

namespace TestWpfApplication
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = DataLibrary.Customer.CreateCustomers();

        }


    }
}

 

Selector.IsSynchronizedWithCurrentItem

http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=KO-KR&k=k(SYSTEM.WINDOWS.CONTROLS.PRIMITIVES.SELECTOR.ISSYNCHRONIZEDWITHCURRENTITEM);k(VS.XAMLEDITOR);k(TargetFrameworkMoniker-%22.NETFRAMEWORK%2cVERSION%3dV4.0%22)&rd=true

 

 

ex) 고객 주문의 상세주문을 보고싶다면?

image
Oders 아래의 데이터를 가지고 오고 싶다면

image

이렇게 구현해주면된다.

xaml

<UserControl x:Class="DragAndDropSimple.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Width="400" Height="300">
  <Canvas x:Name="rootCanvas"
  Width="640"
  Height="480"
  Background="Gray"
  >
    <!-- You can drag this rectangle around the canvas. -->
    <Rectangle
    MouseLeftButtonDown="Handle_MouseDown"
    MouseMove="Handle_MouseMove"
    MouseLeftButtonUp="Handle_MouseUp"
    Canvas.Left="30" Canvas.Top="30" Fill="Red"
    Width="50" Height="50" />
  </Canvas>

</UserControl>

코드

// Global variables used to keep track of the 
// mouse position and whether the object is captured
// by the mouse.
bool isMouseCaptured;
double mouseVerticalPosition;
double mouseHorizontalPosition;

public void Handle_MouseDown (object sender, MouseEventArgs args) 
{
    Rectangle item = sender as Rectangle;
    mouseVerticalPosition = args.GetPosition(null).Y;
    mouseHorizontalPosition = args.GetPosition(null).X;
    isMouseCaptured = true;
    item.CaptureMouse();
}

public void Handle_MouseMove(object sender, MouseEventArgs args) 
{
    Rectangle item = sender as Rectangle;
    if (isMouseCaptured) 
    {

        // Calculate the current position of the object.
        double deltaV = args.GetPosition(null).Y - mouseVerticalPosition;
        double deltaH = args.GetPosition(null).X - mouseHorizontalPosition;
        double newTop = deltaV + (double)item.GetValue(Canvas.TopProperty);
        double newLeft = deltaH + (double)item.GetValue(Canvas.LeftProperty);

        // Set new position of object.
        item.SetValue(Canvas.TopProperty, newTop);
        item.SetValue(Canvas.LeftProperty, newLeft);

        // Update position global variables.
        mouseVerticalPosition = args.GetPosition(null).Y;
        mouseHorizontalPosition = args.GetPosition(null).X;
    }
}

public void Handle_MouseUp(object sender, MouseEventArgs args) 
{
    Rectangle item = sender as Rectangle;
    isMouseCaptured = false;
    item.ReleaseMouseCapture();
    mouseVerticalPosition = -1;
    mouseHorizontalPosition = -1;
}

MS 예제 실행화면

로그인 사용자를  선택할때마다 배경 밑 컨트롤의 스타일이 바뀐다.

image

image

image

 

프로젝트구성

image

Resources_*.xaml 파일은 각각의 컨트롤의 스타일을 가지고 있다.

예로 버튼의 스타일을 보면

Resources_Default.xaml

  <Style x:Key="ButtonStyler"
         TargetType="{x:Type Button}">
    <Setter Property="FontFamily"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontFamilyKey}}" />
    <Setter Property="FontSize"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontSizeKey}}" />
    <Setter Property="FontStyle"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontStyleKey}}" />
    <Setter Property="FontWeight"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontWeightKey}}" />
    <Setter Property="Foreground"
            Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
    <Setter Property="HorizontalContentAlignment"
            Value="Center" />
    <Setter Property="VerticalContentAlignment"
            Value="Center" />
    <Setter Property="ClipToBounds"
            Value="True" />
    <Setter Property="Padding"
            Value="2" />
    <Setter Property="Margin"
            Value="10" />
    <Setter Property="Height"
            Value="30" />
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
          <Grid>
            <Rectangle x:Name="GelBackground"
                       Opacity="1"
                       RadiusX="4"
                       RadiusY="4"
                       Fill="{TemplateBinding  Background}"
                       Stroke="Black"
                       StrokeThickness="1" />
            <ContentPresenter x:Name="ContentSite"
                              Margin="{TemplateBinding Padding}"
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />
          </Grid>
          <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver"
                     Value="true">
              <Setter Property="Rectangle.Fill"
                      Value="#cccccc"
                      TargetName="GelBackground" />
            </Trigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

Resources_Luna.xaml

  <Style x:Key="ButtonStyler"
         TargetType="{x:Type Button}">
    <Setter Property="FontFamily"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontFamilyKey}}" />
    <Setter Property="FontSize"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontSizeKey}}" />
    <Setter Property="FontStyle"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontStyleKey}}" />
    <Setter Property="FontWeight"
            Value="{DynamicResource {x:Static SystemFonts.MessageFontWeightKey}}" />
    <Setter Property="Foreground"
            Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
    <Setter Property="HorizontalContentAlignment"
            Value="Center" />
    <Setter Property="VerticalContentAlignment"
            Value="Center" />
    <Setter Property="ClipToBounds"
            Value="True" />
    <Setter Property="Padding"
            Value="2" />
    <Setter Property="Margin"
            Value="10" />
    <Setter Property="Height"
            Value="30" />
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="{x:Type Button}">
          <Grid>
            <Rectangle x:Name="GelBackground"
                       Opacity="1"
                       RadiusX="4"
                       RadiusY="4"
                       Stroke="black"
                       StrokeThickness="1">
              <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0,0"
                                     EndPoint="0,1">
                  <GradientBrush.GradientStops>
                    <GradientStopCollection>
                      <GradientStop Color="white"
                                    Offset="0" />
                      <GradientStop Color="#99ccff"
                                    Offset="1" />
                    </GradientStopCollection>
                  </GradientBrush.GradientStops>
                </LinearGradientBrush>
              </Rectangle.Fill>
            </Rectangle>
            <Rectangle x:Name="GelShine"
                       Margin="2,2,2,0"
                       VerticalAlignment="top"
                       RadiusX="6"
                       RadiusY="6"
                       Opacity="0"
                       Stroke="transparent"
                       Height="15px">
              <Rectangle.Fill>
                <LinearGradientBrush StartPoint="0,0"
                                     EndPoint="0,1">
                  <GradientBrush.GradientStops>
                    <GradientStopCollection>
                      <GradientStop Color="#ccffffff"
                                    Offset="0" />
                      <GradientStop Color="transparent"
                                    Offset="1" />
                    </GradientStopCollection>
                  </GradientBrush.GradientStops>
                </LinearGradientBrush>
              </Rectangle.Fill>
            </Rectangle>
            <ContentPresenter x:Name="ContentSite"
                              Margin="{TemplateBinding Padding}"
                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"/>
          </Grid>
          <ControlTemplate.Triggers>
            <Trigger Property="IsMouseOver"
                     Value="true">
              <Setter Property="Rectangle.Fill"
                      Value="#99ccff"
                      TargetName="GelBackground"/>
              <Setter Property="Rectangle.Opacity"
                      Value="1"
                      TargetName="GelShine"/>
            </Trigger>
          </ControlTemplate.Triggers>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>

각각 버튼의 스타일이 다른것을 알수있다.

비하인드 코드에서 적용하기

특별한거 없고 ResourceDictionary 생성해서

            switch (UserTilesListBox.SelectedIndex)
            {
                case 0:
                    Application.Current.Resources = _defaultTheme;
                    break;

                case 1:
                    Application.Current.Resources = _lunaTheme;
                    break;

               case 2:
                   Application.Current.Resources = _xBoxTheme;
                   break;

                case 3:
                    Application.Current.Resources = _toonsTheme;
                    break; 
            }

사용자 선택시마다 리소스를 적용한다.

namespace LogonScreen
{
    using System;
    using System.Collections;
    using System.IO;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    using System.Windows.Navigation;
    using System.Windows.Markup;
    using System.Windows.Input;
    using System.Windows.Media.Animation; 

    public partial class Default
    {
        private static bool resourceLoaded = false;
        ResourceDictionary _defaultTheme ; //리소스 만들기
        ResourceDictionary _lunaTheme;
        ResourceDictionary _toonsTheme ;
        ResourceDictionary _xBoxTheme;

        private void Init (object sender, System.EventArgs args)
        {           
            _defaultTheme = new Resources_Default();
            _lunaTheme = new Resources_Luna();
            _toonsTheme = new Resources_Toons();
            _xBoxTheme = new Resources_XBox();

            Application.Current.Resources = _defaultTheme;
        }

        private void OnMouseEnter(object sender, MouseEventArgs args)
        {
            resourceLoaded = true;
        }
           
        void ChangeUser (object sender, SelectionChangedEventArgs e)
        {
            if (!resourceLoaded)
                return;

            switch (UserTilesListBox.SelectedIndex)
            {
                case 0:
                    Application.Current.Resources = _defaultTheme;
                    break;

                case 1:
                    Application.Current.Resources = _lunaTheme;
                    break;

               case 2:
                   Application.Current.Resources = _xBoxTheme;
                   break;

                case 3:
                    Application.Current.Resources = _toonsTheme;
                    break; 
            }
        }
    }
}

wpf 에서는 길이가 지맘대로기 떄문에 일일이 지정하기가 피곤하다

그래서 리소스 파일에다가 치수를 정해놓고

가져와서 쓰면 나중에 일괄적으로 길이를 늘릴수도 있고 줄일수도 있다.

 

 

치수 리소스 만들기

image

텍스트 박스 선택

image

옆에 ㅁ 박스를 누른다

image

New Resouce 선택

image

똑같이 두개 만든다.

 

리소스 파일/application 에다가 해두면 다른 .xaml 에서도 사용할수 있다.

 

만들어진 소스 난 두개 만들었다 높이와 넓이

image

 

적용방법

image

텍스트박스 선택

image

로컬리소스 선택

image

아까만든 TextBoxWidth 를 누른다 

끝~

<UserControl x:Class="CloseableHeader"
             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="150" d:DesignWidth="300"  >

 

 

DesignHeight / DesignWidth

WPF / 실버라이트 작업을 할때 Grid 같은 부분에서 특정 폼(위치)에서

아래오 같이 자동으로 크기가 맞게 지정한다.

image

그렇게 되면 아래와 같이 보기가 디게 상그럽따

image  

그래서

임의의 값을 주면

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

image

image

이렇게 디자인하기가 수월해진다. 실제로 프로그램이 실행되면

image

위의 값처럼 실행 된다.

컨트롤의 색깔이라든지 레이아웃을 일관성 있게 만들기 위해

리소스로 등록 해 놓고 쓴다. (Web 의 CSS 랑 비슷하다)

브러시 리소스 간단하게 만드는법

image

컨텐츠를 찍고 나서

image ㅁ 를 클릭하면

아래와 같은 메뉴가 나온다.

image

이름을 지정하고 나서

image

아래에 보면 Local Brush Resources 라고 나타난다.

image

만들어진 브러쉬로 적용하기

image

아무 컨트롤이나 끌어놓는다 위에는 Rectangle 이다

image

Fill 의 ㅁ을 누른다.
image

“ControlBrush” 라고 아까 내가 준 브러쉬 이름 선택

image

색이 반영대따  ㅋ

소스에 가보면

SeaWorkResourceDictionary.xaml 색이 만들어져 있따

image

App.xaml 에서는 전역으로 SeaWorkResourceDictionary.xaml를 어플리케이션
리소스로  사용하기 위해 등록되있다

image

최종 UIimage

출처

http://code.msdn.microsoft.com/wpfsamples#themes

All Samples
This download contains all of the WPF documentation samples in a single package.
Download

Getting Started with WPF

Introduction to Building WPF Applications
This sample provides an introduction to the development of a simple WPF application, and demonstrates controls, images, layout, and data binding.
Download | Getting Started with WPF
Introduction to Building WPF Applications
WPF Controls Gallery Sample
This sample shows common usage scenarios and the default rendering behavior for many user interfaces and layout controls in WPF.
Download | System.Windows.Controls Namespace
WPF Controls Gallery Sample

Application Samples

Video Viewer Demo
This sample creates a video viewing application that demonstrates styling, data binding, and data templating features.
Download | Styling and Templating
Video Viewer Demo
Data Binding Demo
This sample creates a product listing application that allows users to enter items for sale. This sample demonstrates several data binding concepts.
Download | Data Binding Overview
Data Binding Demo
Particle Effects Demo
This sample application demonstrates how to produce particle effects within a System.Windows.Controls.Viewport3D.
Download | Viewport3D Class
Particle Effects Demo
XBAP Hosting Silverlight Sample
This sample demonstrates how to host a Silverlight-based application in a XAML browser application (XBAP) and how to communicate between the host XBAP and the hosted Silverlight-based application.
Download | WPF XAML Browser Applications Overview
XBAP Hosting Silverlight Sample

WPF Windows Samples

MessageBox Sample
This sample demonstrates how to display a message box and get the message box return value.
Download | Dialog Boxes Overview
MessageBox Sample
Dialog Box Sample
This sample demonstrates how to use message boxes and common dialog boxes. This sample also shows how to create and use both modal and modeless dialog boxes.
Download | Dialog Boxes Overview
Dialog Box Sample
Notification Icon Sample
This sample demonstrates how to display an icon in the notification area.
Download | NotifyIcon Class
Notification Icon Sample

WPF Fundamentals

Height Properties Sample
This sample shows the differences among the height-related properties in WPF.
Download | How to: Set the Height Properties of an Element
Height Properties Sample
Width Properties Comparison Sample
This sample shows the differences among the width-related properties in WPF.
Download | How to: Set the Width Properties of an Element
Width Properties Comparison Sample

Input and Commands

Create a Custom RoutedCommand Sample
This sample shows how to create and use a custom System.Windows.Input.RoutedCommand.
Download | Commanding Overview
Create a Custom RoutedCommand Sample

Styles

Introduction to Styling and Templating Sample
This is a simple photo application that is designed to demonstrate how to use styling to create a visually compelling user experience.
Download | Styling and Templating
Introduction to Styling and Templating Sample

Themes

Default WPF Themes
The theme files in this section are created from the resource dictionaries containing each WPF theme and are provided as examples of how to create themes, as well as how to customize existing controls.
Download | System.Windows.Controls Namespace

Threading

Single-Threaded Application with Long-Running Calculation Sample
This sample demonstrates how to keep the UI from becoming non-responsive in single threaded application which performs a long operation.
Download | System.Windows.Threading Namespace
Single-Threaded Application with Long-Running Calculation Sample

Controls

ListView with Multiple Views Sample
This sample shows how to create a System.Windows.Controls.ListView control that displays data in multiple view modes, which include the System.Windows.Controls.GridView and other custom view modes.
Download | ListView Overview
ListView with Multiple Views Sample
TreeListView Sample
This sample shows how to create a custom TreeView that resembles the ListView when it uses the GridView.
Download | TreeView Class
TreeListView Sample
Popup Placement Sample
This sample creates a simple System.Windows.Controls.Primitives.Popup and lets the user position the System.Windows.Controls.Primitives.Popup.
Download | Popup Placement Behavior
Popup Placement Sample

Control Customization

Styling with ControlTemplates Sample
This sample shows the System.Windows.Controls.ControlTemplate examples for the most common WPF controls. If you are replacing the System.Windows.Controls.ControlTemplate of a control, these examples are the best place to get started.
Download | Styling and Templating
Styling with ControlTemplates Sample
NumericUpDown Custom Control with Theme and UI Automation Support Sample
This sample demonstrates how to create a custom control that supports theming and UI automation.
Download | Control Authoring Overview
NumericUpDown Custom Control with Theme and UI Automation Support  Sample
ColorPicker Custom Control Sample
This sample shows how to create a custom control and display it in a dialog window. This sample defines a custom color picker control that enables users to browse colors by their hue, saturation, and brightness.
Download | Dialog Boxes Overview
ColorPicker Custom Control Sample
ResizingAdorner Sample
This sample implements a simple adorner that adds resizing handles to the element to which it is applied.
Download | Adorner Class
ResizingAdorner Sample
Custom Radial Panel Sample
This sample shows how to derive a custom layout object from System.Windows.Controls.Panel that arranges its child elements in a radial pattern.
Download | Layout System
Custom Radial Panel Sample
Create a Custom Content-Wrapping Panel Sample
This sample shows how to override the default layout behavior of the System.Windows.Controls.Panel element.
Download | How to: Create a Custom Panel Element
Create a Custom Content-Wrapping Panel Sample

Layout

WPF Layout Gallery Sample
This sample provides a set of overview documents and samples that visually introduce you to the layout system in WPF.
Download | Layout System
WPF Layout Gallery Sample

Data Binding

Binding Validation Sample
This sample shows how to implement data validation on the UI layer using binding.
Download | How to: Implement Binding Validation
Binding Validation Sample
Introduction to Data Templating Sample
This sample demonstrates how to use System.Windows.DataTemplate, System.Windows.DataTrigger, and System.Windows.Controls.DataTemplateSelector to specify the presentation of your data.
Download | Data Templating Overview
Introduction to Data Templating Sample
Changing a Collection by Using IEditableCollectionView Sample
This sample uses the members that are provided by the System.ComponentModel.IEditableCollectionView interface to add and change items in a System.Windows.Controls.ListView.
Download | IEditableCollectionView Interface
Changing a Collection by Using IEditableCollectionView Sample
Sorting and Filtering Items in a View Sample
This sample shows how to use a collection view to apply a sort order and filtering.
Download | How to: Filter Data in a View
Sorting and Filtering Items in a View Sample

Drag and Drop

Drag and Drop an Object on a Canvas Sample
This example shows how to move objects on a System.Windows.Controls.Canvas using drag and drop. In addition, this sample shows how to apply an adorner and an animation to the object as it is being moved.
Download | Drag and Drop Overview
Drag and Drop an Object on a Canvas Sample
Load a Dropped File Sample
This sample will open and display the contents of a text file dropped on the sample.
Download | DataObject Class
Load a Dropped File Sample
Thumb Drag Functionality Sample
This example shows how to use a System.Windows.Controls.Primitives.Thumb to resize a System.Windows.Controls.Canvas control by responding to the System.Windows.Controls.Primitives.Thumb.DragDelta event.
Download | How to: Use a Thumb to Enable Dragging
Thumb Drag Functionality Sample

Packaging

Reading a Package Sample
This sample shows how to read content, resource, and relationship parts from a XML Paper Specification (XPS) System.IO.Packaging.Package.
Download | Documents in WPF
Reading a Package Sample
Writing a Package Sample
This sample shows how to write content, resource, and relationship parts to a XML Paper Specification (XPS) System.IO.Packaging.Package.
Download | Documents in WPF
Writing a Package Sample
Creating a Package with a Digital Signature Sample
This sample shows how to write a XML Paper Specification (XPS) package with digitally signed content, and then read and validate the signed elements.
Download | PackageDigitalSignatureManager Class
Creating a Package with a Digital Signature Sample

Typography

Advanced Text Formatting Sample
This sample shows how to create and use the Microsoft .NET Framework text engine.
Download | Advanced Text Formatting
Advanced Text Formatting Sample

Brushes

Brushes Sample
This sample shows how to paint with solid colors, gradients, images, and drawings. It shows how to use features common to all brushes, such as the System.Windows.Media.Brush.Transform, System.Windows.Media.Brush.RelativeTransform, and System.Windows.Media.Brush.Opacity properties. It also demonstrates how to animate System.Windows.Media.SolidColorBrush and System.Windows.Media.GradientBrush objects.
Download | WPF Brushes Overview
Brushes Sample
ImageBrush Sample
This sample shows how to use an System.Windows.Media.ImageBrush to paint an area with an image. It also shows how to create patterns from an image.
Download | WPF Brushes Overview
ImageBrush Sample
VisualBrush Sample
This sample shows how to use a System.Windows.Media.VisualBrush to paint an area with text, controls, and shapes. It also shows how to use a visual brush to magnify a portion of the screen and create a reflection.
Download | WPF Brushes Overview
VisualBrush Sample
Opacity Masking Sample
This sample shows how to create opacity masks and apply them to elements.
Download | DrawingBrush Class
Opacity Masking Sample

Geometries

Geometries Sample
This sample shows how to create and use geometries.
Download | Geometry Overview
Geometries Sample
Point Sample
This sample demonstrates the different operations of the System.Windows.Point structure.
Download | Point Structure
Point Sample
Vector Sample
This sample shows how to use the various methods and properties of the System.Windows.Vector structure.A list of radio buttons is created that selects the operation to perform.
Download | Vector Structure
Vector Sample
Clip Region Sample
This sample shows how to define System.Windows.UIElement.Clip regions.
Download | How to: Animate a Clip Region
Clip Region Sample
Converter Sample
This sample shows how to use the converter classes to convert an instance of a type into a string.
Download | PointConverter Class
Converter Sample

Images

ImageView Sample
This sample shows a simple image viewing utility using the System.Windows.Controls.Image and System.Windows.Media.Imaging.BitmapImage objects.
Download | Imaging Overview
ImageView Sample
Win32 Sample Codec
This sample demonstrates how to create a custom codec can be built using the unmanaged WPF Imaging Component API.
Download | Imaging Overview

Shapes

Shape Elements Sample
This sample shows how to draw by using the following System.Windows.Shapes.Shape elements:
System.Windows.Shapes.Ellipse, System.Windows.Shapes.Line, System.Windows.Shapes.Path, System.Windows.Shapes.Polygon, System.Windows.Shapes.Polyline, and System.Windows.Shapes.Rectangle.
Download | WPF Graphics, Animation, and Media Overview
Shape Elements Sample

Transformations

2-D Transforms Sample
This sample shows how to create, use, and animate two-dimensional transforms.
Download | Transforms Overview
2-D Transforms Sample
Matrix Sample
This sample shows how to use the various methods and properties of the System.Windows.Media.Matrix structure.
Download | Matrix Structure
Matrix Sample

3-D Graphics

3-D Hit Testing Sample
This sample provides information about hit testing on an animated 3-D model.
Download | How to: Hit Test in a Viewport3D
3-D Hit Testing Sample
3-D Lights Sample
This sample shows how to use the various methods and properties of the System.Windows.Media.Media3D.AmbientLight, System.Windows.Media.Media3D.DirectionalLight, and System.Windows.Media.Media3D.PointLight, objects.
Download | System.Windows.Media.Media3D Namespace
3-D Lights Sample
3-D Mesh Sample
This sample shows how to build meshes and group models to compose a 3-D scene in procedural code.
Download | Point3DCollection Class
3-D Mesh Sample
3-D Scene Sample
This sample shows how to create and draw in a 3-D scene.
Download | 3-D Graphics Overview
3-D Scene Sample
3-D Scene Animation Rotation Code Sample
This sample shows how to animate a rotation transformation on a 3-D model in procedural code.
Download | PerspectiveCamera Class
3-D Scene Animation Rotation Code Sample
3-D Solids Sample
This sample applies images to several different 3-D models and shows how to re-use application resources in building a 3-D scene.
Download | System.Windows.Media.Media3D Namespace
3-D Solids Sample
Animated Rotation Markup Sample
This sample shows how to animate a rotation transformation on a 3-D model.
Download | 3-D Transformations Overview
Animated Rotation Markup Sample
MatrixTransform3D Viewer Sample
This sample provides a 3-D scene and some basic controls to demonstrate the effects of different Matrix3D values on transformations applied to a 3-D model.
Download | 3-D Transformations Overview
MatrixTransform3D Viewer Sample
Point3D Sample
This sample shows how to use the various methods and properties of the System.Windows.Media.Media3D.Point3D structure.
Download | Point3D Structure
Point3D Sample
Point4D Sample
This sample shows how to use the various methods and properties of the System.Windows.Media.Media3D.Point4D structure.
Download | Point4D Structure
Point4D Sample
Quaternion Viewer Sample
This sample provides a 3-D scene and some basic controls to demonstrate the effects of different quaternion values on transformations applied to a 3-D model.
Download | System.Windows.Media.Media3D Namespace
Quaternion Viewer Sample
Size3D Sample
This sample shows how to use the various methods and properties of the System.Windows.Media.Media3D.Size3D structure.
Download | Size3D Structure
Size3D Sample
Vector3D Sample
This sample shows how to use the various methods and properties of the System.Windows.Media.Media3D.Vector3D structure.
Download | Vector3D Structure
Vector3D Sample
UIElement3D Sphere Sample
This sample shows how to create a Sphere class that derives from System.Windows.UIElement3D.
Download | UIElement3D Class
UIElement3D Sphere Sample
Interactive 2-D on 3-D Sample
This sample demonstrates how to place interactive 2-D content, a button in this case, on a 3D object, using the System.Windows.Media.Media3D.Viewport2DVisual3D class.
Download | Viewport2DVisual3D Class
Interactive 2-D on 3-D Sample
Handling Events in 3-D Sample
This sample demonstrates how to create 3-D objects that respond to events using the System.Windows.Media.Media3D.ContainerUIElement3D and System.Windows.Media.Media3D.ModelUIElement3D classes. In particular, this sample creates two cubes that respond to mouse-down events.
Download | UIElement3D Class
Handling Events in 3-D Sample

Animations

Animation Example Gallery
This sample shows how to animate a variety of objects, include text, 2-D transforms, and 3-D transforms. It also demonstrates splined interpolation, path animations, and custom animations.
Download | Animation Overview
Animation Example Gallery
Animating the Opacity of an Element Sample
This sample shows how to animate the System.Windows.UIElement.Opacity of an element.
Download | How to: Animate the Opacity of an Element or Brush
Animating the Opacity of an Element Sample
Animation Timing Behavior Sample
This sample shows how to specify when an animation starts, how many times it repeats, whether it accelerates or decelerates, and other timing behaviors.
Download | Timing Behaviors Overview
Animation Timing Behavior Sample
Custom Animation Sample
This sample shows how to create custom animations that simulate bouncing and other interesting effects.
Download | Custom Animations Overview
Custom Animation Sample
From, To, and By Animation Target Values Sample
This sample shows how to use the System.Windows.Media.Animation.DoubleAnimation.From, System.Windows.Media.Animation.DoubleAnimation.To, and System.Windows.Media.Animation.DoubleAnimation.By values of an animation.
Download | From/To/By Animations Overview
From, To, and By Animation Target Values Sample
KeyFrame Animation Sample
This sample shows how to use key frame animations to animate along a set of target values.
Download | Key-Frame Animations Overview
KeyFrame Animation Sample
Key Spline Animation Sample
This sample enables you to interactively adjust the key spline of a System.Windows.Media.Animation.DoubleAnimationUsingKeyFrames.
Download | Key-Frame Animations Overview
Key Spline Animation Sample
Path Animation Sample
This sample shows how to animate an object along a geometric path.
Download | Path Animations Overview
Path Animation Sample

Visual Layer Programming

Using the CompositionTarget Sample
This sample illustrates how to use System.Windows.Media.CompositionTarget object to create custom drawings or animations based on a per-frame callback.
Download | How to: Render on a Per Frame Interval Using CompositionTarget
Using the CompositionTarget Sample
Hit Test Using DrawingVisuals Sample
This sample demonstrates how to use System.Windows.Media.DrawingVisual objects to create lightweight graphics. The sample also shows how to implement hit testing at the visual object level.
Download | Using DrawingVisual Objects
Hit Test Using DrawingVisuals Sample
Hit Test with Win32 Interoperation Sample
This sample demonstrates how to use the default hit testing support in the visual layer of WPF.
Download | Hit Testing in the Visual Layer
Hit Test with Win32 Interoperation Sample

Globalization and Localization

Globalization Homepage Sample
This example demonstrates how to build and localize a Homepage.
Download | WPF Globalization and Localization Overview
Globalization Homepage Sample
LocBaml Tool Sample
This sample demonstrates how to use the LocBaml tool to parse input files to create localizable resources and generate a localized binary. The C# files build the tool and the XAML files build a DLL to use as input for the LocBaml tool.
Download | WPF Globalization and Localization Overview
LocBaml Tool Sample

Migration and Interoperability

Arranging Windows Forms Controls in WPF Sample
This sample shows how to use WPF layout features to arrange Windows Forms controls in a hybrid application.
Download | Walkthrough: Arranging Windows Forms Controls in WPF
Arranging Windows Forms Controls in WPF Sample
Enabling Visual Styles in a Hybrid Application Sample
This sample shows how to enable Microsoft Windows XP visual styles on a Windows Forms control hosted in a WPF-based application.
Download | How to: Enable Visual Styles in a Hybrid Application
Enabling Visual Styles in a Hybrid Application Sample
Hosting a Simple WPF Control in Windows Forms Sample
This sample demonstrates how you can host a simple WPF control on Windows Forms. It shows how to receive events and acquire data from the control and modify the control's properties.
Download | How to: Host a WPF Control in Windows Forms by Using ElementHost
Hosting a Simple WPF Control in Windows Forms Sample
Hosting a Win32 ListBox Control in WPF Sample
Hosts a Win32 ListBox control on a WPF page. This sample shows how to create and host the control, and how to send and receive messages.
Download | Walkthrough: Hosting a Simple Win32 Control in a WPF Application
Hosting a Win32 ListBox Control in WPF Sample
Hosting a Windows Forms Composite Control in WPF Sample
This sample shows you how to host a Windows Forms control in a WPF page. It also shows how to receive events from the control and modify the control's properties from the page.
Download | Walkthrough: Hosting a Windows Forms Composite Control in WPF
Hosting a Windows Forms Composite Control in WPF Sample
Hosting a Windows Forms Control in WPF Sample
This sample demonstrates how to host a Windows Forms control on a WPF page.
Download | Walkthrough: Hosting a Windows Forms Control in WPF
Hosting a Windows Forms Control in WPF Sample
Hosting a Windows Forms Control in WPF by Using XAML Sample
This sample demonstrates how to host a Windows Forms control on a WPF page by using XAML.
Download | Walkthrough: Hosting a Windows Forms Control in WPF by Using XAML
Hosting a Windows Forms Control in WPF by Using XAML Sample
Hosting WPF Content in a Win32 Window Sample
This sample hosts a WPF page in a Win32 window. The sample shows how to create and host the control, and how to handle communication between the page and the host window.
Download | Walkthrough: Hosting WPF Content in a Win32 Application
Hosting WPF Content in a Win32 Window Sample
Hosting a WPF Composite Control in Windows Forms Sample
This sample demonstrates how to host a WPF System.Windows.Controls.UserControl in a Windows Forms control or form.
Download | Walkthrough: Hosting a WPF Composite Control in Windows Forms
Hosting a WPF Composite Control in Windows Forms Sample
Localizing a Hybrid Application Sample
This sample shows how to localize WPF elements in a Windows Forms-based hybrid application.
Download | Walkthrough: Localizing a Hybrid Application
Localizing a Hybrid Application Sample
Mapping Properties Using the ElementHost Control Sample
This sample shows how to use the System.Windows.Forms.Integration.ElementHost.PropertyMap property to map Windows Forms properties to corresponding properties on a hosted WPF element.
Download | Walkthrough: Mapping Properties Using the ElementHost Control
Mapping Properties Using the ElementHost Control Sample
Mapping Properties Using the WindowsFormsHost Element Sample
This sample shows how to use the System.Windows.Forms.Integration.WindowsFormsHost.PropertyMap property to map WPF properties to corresponding properties on a hosted Windows Forms control.
Download | Walkthrough: Mapping Properties Using the WindowsFormsHost Element
Mapping Properties Using the WindowsFormsHost Element Sample
Win32 Clock Interoperation Sample
This sample demonstrates how to host a WPF control inside of a Win32 application.
Download | Tutorial: Create a Win32 Application Hosting WPF Content
Win32 Clock Interoperation Sample
Hosting a Win32 HWND in WPF Sample
This sample shows how to put an hwnd inside a WPF application.
Download | WPF and Win32 Interoperation Overview
Hosting a Win32 HWND in WPF Sample

+ Recent posts