블로그 이미지
Sunny's

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 31

Notice

2011. 9. 26. 15:23 WPF, Silverlight

The IIS Live Smooth Streaming extension for Internet Information Services (IIS) 7 allows you to set up a Web server as a Live Smooth Streaming server that delivers compelling, uninterrupted live video streams that instantly adjust quality (bit rate) to match changing network and CPU conditions at the client.

Live Smooth Streaming enables adaptive streaming of live events to Smooth Streaming-compatible clients, such as Microsoft Silverlight. Using HTTP to deliver a live Web broadcast leverages the scale of existing HTTP networks by keeping content close to the user and making true HD (720p+) a realistic option for Web broadcasts. The additional advantage of using HTTP-based delivery for live events is that the existing HTTP infrastructure provides much more availability. For many popular live Web broadcasts, content providers and content distribution networks (CDNs) want to know how much capacity they can dedicate on their resource-constrained streaming networks. By using their primary HTTP networks, which are typically 10-to-20-times larger than their streaming networks, they don't have to worry about maximizing network capacity and limiting the number of users for live events.

A Live Smooth Streaming server sources content from Live Smooth Streaming-capable encoders for delivery to Smooth-Streaming compatible clients. In addition to Microsoft Expression Encoder, there are many third-party encoding solutions available for encoding both live and on-demand Smooth Streaming video in production environments. To help you determine which encoding solution is best-suited for your Smooth Streaming configuration, see the list of our encoding parters.

In this walkthrough:

Setting Up a Live Smooth Streaming Web Server

To install IIS Live Smooth Streaming, see the IIS Media Services Readme Installation Notes. This walkthrough describes how to set up a Live Smooth Streaming server using IIS Live Smooth Streaming in IIS Media Services 4.0, so be sure to select this version of IIS Media Services for installation.

After installation is completed, to verify that the Live Smooth Streaming extension is installed correctly, click the server name in the Connections pane in IIS Manager and locate the Live Smooth Streaming icon in the Media Services area.

Note If IIS Manager was running during the installation process, you may need to restart it to see Live Smooth Streaming.

Creating a Live Smooth Streaming Publishing Point

This section describes how to create a publishing point that can accept a live broadcast from a Live Smooth Streaming-capable encoder.

  1. In IIS Manager, select the desired Web Site or virtual directory, and then double-click the Live Smooth Streaming Publishing Points icon.

  2. On the Live Smooth Streaming Publishing Points page, in the Actions pane, click Add.

  3. In the Add Publishing Point dialog box, on the Basic Settings tab, enter the following information:

    • File name. Enter a name for the Live Smooth Streaming publishing point definition file. In this example and throughout the rest of this walkthrough, we use the file name LiveSmoothStream. If you specify a different file name, be sure to substitute it appropriately as you follow the steps in this walkthrough.
    • Estimated duration. If known, enter the duration (in hours:minutes:seconds) of the live event so that the Silverlight-based client can scale its Seek bar to the length of the content. In our example, we use an event duration of 1 hour (01:00:00).
    • Live source type. In our example, the Live Smooth Streaming server is an "origin server" that receives the content that is pushed to it from an encoder; therefore, we select the default Push option.

      Note The Pull option for Live source type configures the publishing point to "pull" content from a publishing point on another Live Smooth Streaming server. This is a common configuration for syndication of content. For more information, see Live Smooth Streaming for IIS 7 - Syndicating Content between Servers.
  4. On the Advanced Settings tab, select the Start publishing point automatically upon first client request check box. This setting allows an encoder to connect to the publishing point when the broadcast starts. Connection errors might occur if you don't enable this setting.


    For more information about the additional settings that you can configure on the Advanced Settings tab, see Add/Edit Dialog Box.
  5. If you want to deliver live streams to Apple® mobile digital devices, on the Mobile Devices tab, select the Enable output to Apple mobile digital devices check box.


    Important Before proceeding, be sure to check out the the following walkthrough article for more information about the requirements and publishing point configuration for Apple HTTP Live Smooth Streaming: Apple HTTP Live Streaming with IIS Media Services.
  6. In the Add Publishing Point dialog box, click OK. A newly created Live Smooth Streaming publishing point definition file named LiveSmoothStream.isml is added to the Web site root.

  7. On the Live Smooth Streaming Publishing Points page, select the publishing point, and then in the Actions pane, click Start Publishing Point.

  8. The publishing point State value changes from Idle to Starting, which means it is waiting for external data (in this case, a live stream pushed to it from an encoder).


    Because we have not yet configured an encoder to push live streams to the publishing point, the Publishing Point Summary panel shows that there are no incoming streams.

    Note The Summary panel for Live Smooth Streaming publishing points is new in IIS Media Services 4.0 and is used to display summary information about the live Smooth Streams that are received from all live sources (such as encoders or other Live Smooth Streaming publishing points) by the selected publishing point. You can also view details about the tracks within all of the live streams, and stream origin and destination information, in a new Publishing Point Details page. For more information, see Viewing Publishing Point Details.

    Note After the publishing point begins receiving data from an encoder, its State value changes to Started. However, due to a known issue, the change in the State value isn't visible until after you refresh the Live Smooth Streaming Publishing Points page in IIS Manager.
  9. See the next section, which describes how to configure Microsoft Expression Encoder to push data to this publishing point.

Pushing a Stream to the Live Smooth Streaming Publishing Point

This section describes how to create a Live Smooth Streaming broadcast in Microsoft Expression Encoder 4 and push it to the Live Smooth Streaming publishing point that you configured in the previous section. The steps in this section outline a general workflow, with details only on the specific tasks that you need to create Live Smooth Streaming output. For detailed information about how to create a live broadcast from various live and file-based sources in Expression Encoder 4, including how to assemble a complete program, encode it, encrypt it with Digital Rights Management (DRM), and instantly distribute it to your audience using Smooth Streaming technology, see Creating a Live Broadcasting Project.

Important If you enabled the publishing point to stream content to Apple devices, such as iPhone® and iPad™ devices, be sure to review the encoding requirements and settings outlined in Apple HTTP Live Streaming with IIS Media Services.

Note Live Smooth Streaming is available only in Microsoft Expression Encoder Pro.

  1. Start Expression Encoder (click Start > All Programs > Microsoft Expression > Microsoft Expression Encoder 4).
  2. In the Load a new project dialog box, select Live Broadcasting Project, and then click OK.

  3. Set up the source to use for your live broadcast. For File Sources, you can use audio or video sources in any file format that Expression Encoder can import. For Live Sources, you can connect multiple camera devices, such as USB webcams or FireWire (IEEE 1394) digital video cameras. Although you can connect multiple live sources, you can stream only one at a time.
  4. On the Presets tab, choose an encoding preset that supports the bit rates and encoding requirements for your Live Smooth Streaming Scenario. Be sure to choose a preset with IIS Smooth Streaming in the preset name, and then click Apply.


    To find out more information about a preset, such as the numbers of streams in the output and the codecs used, hover your mouse pointer over a preset name. The preset information is displayed in a box.

    Note Clicking the Apply button automatically updates the Output Format, Video, and Audio settings on the Encode tab with the values used by the selected preset.


    You can choose to not select a preset and specify your own values for the Output Format, Video, and Audio options on the Encode tab instead.
  5. On the Output tab, select the Streaming check box to activate streaming.


    With Streaming selected on the Output tab, your only choice for publishing your content is to use the Publishing Point option, which is automatically selected (If it isn't selected, select it). In the Location box, type the URL of the Live Smooth Smooth Streaming publishing point that you want to publish your live broadcast to.


    URL syntax: http://ServerName/SiteName/DirectoryName/PublishingPointDefinitionFileName.isml

    For the example Live Smooth Streaming publishing point that we created in the previous section, the URL would be:

    http://IISMedia-Server/LiveSmoothStream.isml

    Note You can click the Connect button to test the connection to the publishing point after you specify its URL in the Location box. The publishing point must be started for the connection to be validated.
  6. If you want to add Digital Rights Management (DRM) to your content, select the Digital Rights Management check box on the Output tab, and then type the License URL (the server that supplies the license), the Key ID, and the Key Seed (available from the license provider). For more information, see Set DRM options.

    Note The license provided for a Live Smooth Streaming session is non-persistent, meaning that after the user closes the client application being used to view the Web broadcast, the license expires.

    Important You should not use this setting if you want to stream the content to Apple devices. To provide protected content to Apple devices, you can configure the Live Smooth Streaming publishing point to encrypt the content by using the Advanced Encryption Standard (AES) with a 128-bit key. For more information about how to configure Apple AES-128 encryption, see Add/Edit Dialog Box.
  7. Click Cue to enable your source for broadcasting (a cued file source is shown in the following figure)...


    ...and then click Start to begin your live broadcast.


    As the broadcast runs, you can monitor Statistics and Connections data in the corresponding panels.

Serving the Live Stream to Clients

This section describes how to use the Microsoft Silverlight Media Framework 2.0 SmoothStreamingPlayer.XAP, a sample player that can easily be embedded in your Web site to enable client playback of Smooth Streaming media.

Important Apple devices use an HTML 5 Web page to play the Live Smooth Streaming presentation. If you enabled the publishing point to stream content to Apple devices, see Creating an HTML 5 page for use in Safari.

Note The latest version of Microsoft Silverlight must be installed on the client computer that you want to use to observe Live Smooth Streaming.

  1. On the Web server, click the following link to download the sample player executable file: SmoothStreamingPlayer.exe.
  2. To extract the sample player files immediately, click Run.
    -or-
    To copy the sample player files to your Web server in order to extract them at a later time, click Save, and then open the file from the saved location.
  3. When you are prompted for a location to store the extracted sample player files, enter the directory path of a temporary folder on your desktop. For example:

  4. Open the temporary desktop folder, review the terms in the End User License Agreement (EULA) file, and then right-click the zipped folder and click Extract All to extract the sample player files.

  5. When you are asked to select the destination folder to which the sample player files will be extracted, select a Web site or virtual directory that you want to use for client access to the live broadcast. In our example, we extract the files to the default Web site, which also contains the Live Smooth Streaming publishing point definition file (LiveSmoothStream.isml).

  6. To view the sample player files, in IIS Manager, open the Web site or virtual directory in Content View.


    The following files are included in the download:
    • Smooth Streaming Player-ReadMe.doc. Configuration instructions.
    • SmoothStreamingPlayer.html. A sample Web page in which you must update the media reference to your live broadcast, and if necessary, width and height attributes to achieve a presentation size that fits your Web site design.
    • SmoothStreamingPlayer.xap. A sample Smooth Streaming player.
  7. In a text editor, such as Notepad, open SmoothStreamingPlayer.html and update the mediaurl attribute value with the fully qualified URL of the Live Smooth Streaming publishing point definition (.isml) file. In our example, this is:

    http://IISMedia-Server/LiveSmoothStream.isml/manifest

    If necessary, also update the width and height attributes to appropriate values for your Web site design. For complete instructions, see the Readme file (Smooth Streaming Player-ReadMe.doc).
  8. In a Web browser on the client computer, download the sample Web page from the Web server and begin viewing the stream. In our example, in the Web browser address bar, type http://IISMedia-Server/SmoothStreamingPlayer.html.

    The Live Smooth Streaming broadcast opens in the Web browser, using the Silverlight browser plug-in for Live Smooth Streaming.

For more information about how to to build rich Silverlight user experiences that take full advantage of live and on-demand IIS Smooth Streaming capabilities, see the Smooth Streaming Client Web page.

출처 : http://learn.iis.net/page.aspx/620/getting-started-with-iis-live-smooth-streaming/

posted by Sunny's
2011. 8. 8. 11:01 WPF, Silverlight

오늘은 Silverlight를 주제와 관련된 정보를 정리했습니다.
아래에 보는 링크는 Silverlight를 배울 수 있는 링크를 정리했습니다.

아래 내용만 잘 따라가셔도 충분한 기본 스킬을 확보 할 수 있을 만큼 좋은 자료들 입니다.

Silverlight 4 Business Apps: Module 1 - Introduction Hands On Labs
Silverlight 4 Business Apps: Module 2 - Event Manager using WCF RIA Service Hands On Labs
Silverlight 4 Business Apps: Module 3 - Authentication Validation, MVVM, Implicit Styles and RichTextBox Lab Hands On Labs
Silverlight Business Apps: Module 3.1 - Authentication Video
Silverlight Business Apps: Module 3.2 - MVVM Video
Silverlight Business Apps: Module 3.3 - Validation Video
Silverlight Business Apps: Module 3.4 - implicit Style Video
Silverlight Business Apps: Module 3.5 - RichTextBox Video
Silverlight Business Apps: Module 4 - Webcam, Drag and Drop, and Clipboard Lab Hands On Labs
Silverlight Business Apps: Module 4.1 - Webcam Video
Silverlight Business Apps: Module 4.2 - Drag and Drop in Silverlight Video
Silverlight Business Apps: Module 5 - DataGrid, Grouping Right Mouse Click Lab Hands On Labs
Silverlight Business Apps: Module 5.1 - Grouping and Binding Video
Silverlight Business Apps: Module 5.2 - Layout Visual States Video
Silverlight Business Apps: Module 5.3 - Right Mouse Click Video
Silverlight Business Apps: Module 6 - Multipage Printing Hands On Labs
Silverlight Business Apps: Module 6.1 - Printing and the ViewBox Video
Silverlight Business Apps: Module 6.2 - Multi Page Printing Video
Silverlight Business Apps: Module 7 - Out of Browser, Toasts, native Integration Lab Hands On Labs
Silverlight Business Apps: Module 7.1 - Out of Browser Video
Silverlight Business Apps: Module 7.2 - NotificationWindow(Toasts) for Elevated Trust Out of Browser Applications Video
Silverlight Business Apps: Module 7.3 - Out of Browser Window Placement Video
Silverlight Business Apps: Module 7.4 - Out of Browser Trusted Application Overview Video
Silverlight Business Apps: module 8 - Advanced OOB, Custom Window Chrome, Silent Installs, Digital Signing, and MEF Lab Hands On Labs
Silverlight Business Apps: Module 8.1 - Custom Window Chrome for Elevated Trust out of Browser Applications Hands On Labs
Silverlight Business Apps: Module 8.2 - Window Closing Event for Out of Browser Applications Hands On Labs
Silverlight Business Apps: Module 8.3 - Silent Install of Out of Browser Applications Video
Silverlight Business Apps: Module 8.4 - Digitally Singing Out of Browser Applications Video
Silverlight Business Apps: Module 8.5 - The Value of MEF with Silverlight Video

아래 자료는 추가적인 Hands On Lab 입니다.

Silverlight RichTextBox Lab Hands On Labs
Silverlight Validation, Binding, DataFrom and DataGrid lab Hands On Labs
Webcam in Silverlight lab Hands On Labs
What's New in Silverlight 4 Hands On Labs
Multi Touch in Silverlight lab Hands On Labs
Out of Browser with COM Interop Lab Hands On Labs

앞으로도 자주 뵙겠습니다.
감사합니다.

출처 : http://blogs.msdn.com/b/eva/archive/2011/08/08/eva-news-letter-2011-08-08-silverlight.aspx

posted by Sunny's
2010. 12. 17. 19:53 WPF, Silverlight

Important methods, properties for OOB in Silverlight

Application.IsRunningOutOfBrowser (Gets a value that indicates whether the application was launched from the out-of-browser state.)
Application.Install() (Attempts to install the application so that it can run outside the browser.)
Application.InstallState (Gets the current out-of-browser installation state of the application.)
InstallState Enumeration (Defines constants that indicate the installation state of an application that is configured to run outside the browser.)

A complete guidance on Out of Browser Support in Silverlight.

Where to find installed OOB applications?

A list of all silverlight applications is available in a hidden folder
C:\Users\{user name}\AppData\LocalLow\Microsoft\Silverlight\OutOfBrowser\
Notice also a folder sibling …\Silverlight\is\ which is an isolated storage for running Silverlight apps.

Name of the files in this folder is done by the address of the location (e.g. localhost, microsoft.com). Most of these files are empty, but those which are installed for OOB mode has some information within. Open that file and you will see the ID of the application and the whole URL where the original (web version) is located. ID with name of file creates ApplicationID (e.g. 972856442.localhost, 3326975874.zdechovan.com) which we will use to launch our application in a section below.

How to launch a Silverlight OOB?

There is an application sllauncher.exe, that is used to launch Silverlight application in Out of Browser mode. This application is located in C:\Program Files\Microsoft Silverlight\sllauncher.exe.

To run a silverlight application you have to pass some parameters to this sllauncher, if you try to run it without any of them, you’ll see the usage pattern:

  1. SLLauncher.exe [app_id] [debug] [/install:<file path to XAP>]   
  2. [/emulate:<file path to XAP>] [/overwrite] /origin:<original app uri>   
  3. /uninstall /shortcut:<desktop|startmenu|desktop+startmenu|none> [/pid]  

You can experiment with a lots of variations of parameters set up if you wish, for me, the most importat is to set a shortcut, which will launch our application. It’s because I experienced a problem, that after install from application the shortcut was corrupted and didn’t work.

Working shortcut should contain {path to sllauncher}/sllauncher.exe {ApplicationId} so for example C:\Program Files\Microsoft Silverlight\sllauncher.exe 972856442.localhost in my case.

If you want to debug your OOB application simply add a debug parameter.

I found an article Installing Silverlight applications without the browser involved by Tim Heuer about how to use  sllauncher to install/uninstall a silverlight application.

posted by Sunny's
2010. 5. 31. 14:33 WPF, Silverlight


Smooth Streaming UI : http://silverlightsdk.net/37
Smooth Streaming 설정 : http://silverlightsdk.net/38

posted by Sunny's
2010. 3. 15. 13:23 WPF, Silverlight

WPF를 처음 사용하시는 분들~ ^^
쉽지 않으셨으리라 생각됩니다. 관련된 테마별로 소스와 문서가 잘 정리되어 있는 링크를 공유합니다.
Visual Studio 2010과 함께 WPF도 4.0으로 업그레이드 될 예정입니다.

http://code.msdn.microsoft.com/wpfsamples 
posted by Sunny's
2009. 10. 14. 11:40 WPF, Silverlight

Silverlight 도메인 간 정책(clientaccesspolicy.xml) 파일을 설정
 
 
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="*">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>


 
posted by Sunny's
2009. 4. 16. 11:28 WPF, Silverlight

[XAML]

<Grid Width="320" Height="480">
    <Grid.Background>
        <ImageBrush ImageSource="Background.jpg"/>
    </Grid.Background>
    <Canvas ClipToBounds="True" Margin="0,82,0,40">
        <StackPanel Background="WhiteSmoke" Canvas.Top="0" x:Name="Panel">
            <StackPanel.Resources>
                <Style TargetType="Button">
                    <Setter Property="Height" Value="30"/>
                    <Setter Property="Width" Value="300"/>
                    <Setter Property="Margin" Value="10"/>
                </Style>
            </StackPanel.Resources>
        </StackPanel>   
    </Canvas>
</Grid>

[C#]

void Window1_Loaded(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < 30; i++)
    {
        Button Item = new Button();
        Item.Content = "ITEM #" + i.ToString();
        Panel.Children.Add(Item);
    }

    ScrollPanel ScrollPanel = new ScrollPanel(Panel);

}

[C# - ScrollPanel.cs]

public class ScrollPanel
{

    private const int MinimunRange = 30;
    private const int MinimumTime = 100;

    private FrameworkElement Target { get; set; }
    private FrameworkElement TargetParent { get; set; }

    private Point BeginPoint;
    private Point LastPoint;
    private DoubleAnimation MoveAnimation;
    private double LastMoveTime;

    public ScrollPanel(FrameworkElement TargetElement)
    {
        MoveAnimation = new DoubleAnimation();
        MoveAnimation.Duration = TimeSpan.FromMilliseconds(1000);
        MoveAnimation.DecelerationRatio = 0.8;

        Target = TargetElement;
        TargetParent = Target.Parent as FrameworkElement;
        Target.PreviewMouseMove += new MouseEventHandler(Target_MouseMove);
        Target.PreviewMouseDown += new MouseButtonEventHandler(Target_MouseDown);
        Target.PreviewMouseUp += new MouseButtonEventHandler(Target_MouseUp);

    }
    void Target_MouseUp(object sender, MouseButtonEventArgs e)
    {
        Target.ReleaseMouseCapture();
    }

    void Target_MouseDown(object sender, MouseButtonEventArgs e)
    {
        BeginPoint = e.GetPosition(Target);
        Target.CaptureMouse();
    }
    void Target_MouseMove(object sender, MouseEventArgs e)
    {

        if (e.LeftButton != MouseButtonState.Pressed) return;

        // 너무 빨리 움직였을경우
        if ((DateTime.Now.TimeOfDay.TotalMilliseconds - LastMoveTime) < MinimumTime) return;
        LastMoveTime = DateTime.Now.TimeOfDay.TotalMilliseconds;

        // 마우스가 제자리 일 경우
        Point CurrentPointParent = e.GetPosition(TargetParent);
        if (CurrentPointParent.Y == LastPoint.Y) return;
        LastPoint = CurrentPointParent;

        // 마우스가 너무 적게 움직였을 경우
        Point CurrentPoint = e.GetPosition(Target);
        double MovePosition = (CurrentPoint.Y - BeginPoint.Y);
        if (Math.Abs(MovePosition) < MinimunRange) return;

        MoveAnimation.By = MovePosition*1.5;
        Target.BeginAnimation(Canvas.TopProperty, MoveAnimation);

    }

}

XAML코드와 Window Loaded Event부분은 UI구성에 필요한 부분이므로 설명은 생략하도록 하겠습니다. ScrollPanel Class를 살펴보겠습니다. ScrollPanel은 생성자로 스크롤이 될 Target Control을 입력받으며 내부적으로 Target과 Target의 부모를 가지고 있습니다. 그리고 MouseEvent 가 발생할 경우 에 따라서 움직이는 Animation을 적용시켰습니다. 코드를 보고 이해가 안되는 부분이나 추가 설명이 필요하신 부분은 리플 달아주세요.

아래는 전체 소스코드 파일입니다.

posted by Sunny's
2009. 4. 16. 11:22 WPF, Silverlight

This is the way how I implemented paging among a wrap panel in WPF. For this example I used simple buttons inside the wrap panel. My example dynamically takes the height of the control inside the wrap panel to determine the quantity of controls that the wrap panel must show.

In this example the columns always stay static, 1 column Min and 2 columns Max. You can also create a column function to show dynamically the quantity of columns you want.

The result is this:

This is the window when is loaded:

App sin resize

This is the window when is resized:

App when resized


XAML:

<Window x:Class=”PagingWrapPanel.PagingWithDuff”

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

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

Title=”PagingWithDuff” Height=”250″ Loaded=”Window_Loaded”

MaxHeight=”500″ MinHeight=”120″ MaxWidth=”500″ MinWidth=”500″>

<Grid>

<Grid.RowDefinitions>

<RowDefinition />

<RowDefinition Height=”24″ />

<RowDefinition Height=”26″ />

</Grid.RowDefinitions>

<ItemsControl Grid.Row=”0″ Name=”RowsContainer” Background=”Transparent” ItemsSource=”{Binding}” SizeChanged=”RowsContainer_SizeChanged” >

<ItemsControl.ItemTemplate>

<DataTemplate>

<Label />

</DataTemplate>

</ItemsControl.ItemTemplate>

<ItemsControl.ItemsPanel>

<ItemsPanelTemplate>

<WrapPanel Orientation=”Vertical” IsItemsHost=”True”

Width=”Auto” HorizontalAlignment=”Center” />

</ItemsPanelTemplate>

</ItemsControl.ItemsPanel>

</ItemsControl>

<Grid Grid.Row=”1″ HorizontalAlignment=”Center” >

<Label Name=”label1″ VerticalAlignment=”Top” Height=”Auto” >Page 1 out of 1</Label>

</Grid>

<Grid Grid.Row=”2″ >

<Grid.ColumnDefinitions>

<ColumnDefinition Width=”*”/>

<ColumnDefinition Width=”*” />

</Grid.ColumnDefinitions>

<Button Grid.Column=”0″ x:Name=”btnBack” Click=”btnBack_Click” MaxHeight=”25″ >Back</Button>

<Button Grid.Column=”1″ x:Name=”btnNext” Click=”btnNext_Click” MaxHeight=”25″ >Next</Button>

</Grid>

</Grid>

</Window>

By the way, you must change in the App.xaml the StartupUri string to - StartupUri=”PagingWrapPanel.xaml” -

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.Collections.ObjectModel;

namespace PagingWrapPanel

{

///

/// Interaction logic for Window1.xaml

///

public partial class PagingWithDuff : Window

{

ObservableCollection<Label> collection;

WrapPanel currentPanel;

int rowsInPanel, pagingPressed;

double height;

//RowsContainer SizeChanged event is raised before the Loaded event for this class

//We need to raise Loaded event first, using this variable

bool isLoaded;

public PagingWithDuff()

{

InitializeComponent();

collection = new ObservableCollection<Label>();

isLoaded = false;

//Generate 100 Labels to Page

for (int generator = 1; generator <= 100; generator++)

{

Label newLbl = new Label();

newLbl.Name = “Label” + generator;

newLbl.Content = “Label “ + generator;

newLbl.Width = 160;

newLbl.Background = Brushes.Black;

newLbl.Foreground = Brushes.White;

newLbl.HorizontalContentAlignment = HorizontalAlignment.Center;

collection.Add(newLbl);

}

btnBack.IsEnabled = false;

btnNext.IsEnabled = false;

pagingPressed = 1;

RowsContainer.DataContext = collection;

}

//Calculate how many rows will be showed in the container

public int rowsToShow()

{

currentPanel = VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(VisualTreeHelper.GetChild(RowsContainer, 0), 0), 0) as WrapPanel;

int rows = 0;

height = this.currentPanel.ActualHeight;

double RowControlHeight = 0.0;

//Get the first Visible Label in the Panel and get its Height

for (int iterator = 0; iterator <= collection.Count - 1; iterator++)

{

Visibility isVisible = (Visibility)(currentPanel.Children[iterator] as Label).Visibility;

//If is visible get height and break iteration

if (isVisible == Visibility.Visible)

{

RowControlHeight = (double)(currentPanel.Children[iterator] as Label).ActualHeight;

break;

}

}

rows = (int)Math.Floor((decimal)height / (decimal)RowControlHeight);

return rows;

}

//Shows the controls inside the wrap panel

public void setRowsControlsToShow()

{

bool endOfList = false;

bool startOfList = false;

bool medOfList = false;

bool overflow = false;

int collectionCount = 0;

collectionCount = collection.Count;

//Once the datacontext is displayed, we need to show up only the labels in this case we need

if (RowsContainer.Items.Count > 0)

{

int start = PagingWithDuff.startFromIndex(rowsToShow(), pagingPressed);

int end = PagingWithDuff.endInIndex(start, rowsToShow() * 2);

if (start > collectionCount - 1)

//If this happens, means that the panel have no content to show

{

end = collectionCount - 1;

start = (collectionCount - 1) - rowsToShow();

overflow = true;

}

if (start == 0) startOfList = true;

if (end > collectionCount)

{

end = collectionCount - 1;

endOfList = true;

}

else

{

if (!startOfList && !endOfList) { medOfList = true; }

}

for (int iter = 0; iter <= collectionCount - 1; iter++)

{

Label currentRow = currentPanel.Children[iter] as Label;

if ((iter < start) || (iter > end))

{

currentRow.Visibility = Visibility.Collapsed;

}

else

{

currentRow.Visibility = Visibility.Visible;

}

}

if (endOfList)

{

btnNext.IsEnabled = false;

if (pagingPressed > 1) btnBack.IsEnabled = true;

}

else

btnNext.IsEnabled = true;

if (medOfList)

{

if (end <= collectionCount - 1)

{

btnBack.IsEnabled = true;

}

}

if (startOfList)

{

btnBack.IsEnabled = false;

if ((rowsInPanel * 2) <= collectionCount)

btnNext.IsEnabled = true;

}

if (overflow)

{

btnNext.IsEnabled = false;

pagingPressed -= 1;

}

}

else

{

btnNext.IsEnabled = false;

btnBack.IsEnabled = false;

}

}

public void setPagingInfo()

{

int totalQty = collection.Count;

rowsInPanel = rowsToShow();

int totalPages = (int)Math.Floor((double)totalQty / rowsInPanel);

if (totalPages == 0)

{

totalPages = 1;

btnNext.IsEnabled = false;

btnBack.IsEnabled = false;

}

if (pagingPressed > totalPages)

this.label1.Content = “Page “ + totalPages + ” out of “ + totalPages;

else

this.label1.Content = “Page “ + pagingPressed + ” out of “ + totalPages;

}

private static int startFromIndex(int qtyToShow, int page)

{

if (page == 1) return 0;

return ((page - 1) * qtyToShow);

}

private static int endInIndex(int start, int qtyToShow)

{

return (start + qtyToShow) - 1;

}

private void Window_Loaded(object sender, RoutedEventArgs e)

{

setRowsControlsToShow();

setPagingInfo();

isLoaded = true;

}

private void RowsContainer_SizeChanged(object sender, SizeChangedEventArgs e)

{

if (isLoaded)

{

setRowsControlsToShow();

setPagingInfo();

}

}

private void btnNext_Click(object sender, RoutedEventArgs e)

{

pagingPressed++;

setRowsControlsToShow();

setPagingInfo();

}

private void btnBack_Click(object sender, RoutedEventArgs e)

{

pagingPressed -= 1;

setRowsControlsToShow();

setPagingInfo();

}

}

}

posted by Sunny's
2009. 4. 14. 15:57 WPF, Silverlight

Super cool new thing I learned today. In WPF, we can make it so that the drop down (popup) on a ComboBox displays the data in a ListView. Because of the fact that I believe the DataGrid will eventually overtake the ListView as the gold standard for data display in WPF, we’ll do it both ways.

This tutorial is done entirely in Blend and without a line of code.

Step 0) (for the DataGrid only)

Go to Code Plex and download the WPF Toolkit. Extract to a convenient location.

Right-Click on the References folder in your project tab and click “Add Reference…”

clip_image001

Navigate to the location you extracted the WPFToolkit.dll file, select it and hit OK.
clip_image001[6]

Step 1) Select the ComboBox you wish to change and edit the ControlTemplate by right-clicking and selecting “Edit Control Parts (Template) –> Edit a Copy…”

clip_image001[1]

Step 2) Find the ItemsPresenter. This is what would normally display our ItemsSource.

clip_image001[3]

We’re going to get rid of it. And the ScrollViewer for good measure.

Step 3) Where the ScrollViewer is, put in a ListView or a DataGrid, whichever one you’re using.

clip_image001[5]

Now, go the properties of that ListView or DataGrid and click on the box to the right of “ItemsSource”

clip_image001[11]

and, in the resulting menu, select “Template Binding –> ItemsSource”.

clip_image001[7]

Set the DataContext of the ListView or DataGrid to the DataContext of the parent ComboBox using the same process.

And… you’re done! Open the ComboBox and you will see that you can select items in the ListView or DataGrid in the ComboBox dropdown and see those items change the selection of the ComboBox.

clip_image001[13]

You’ll notice that this is probably not yet an ideal solution. For example, when we select an item, the dropdown doesn’t automatically close. Your best bet is to use the SelectionChanged event to trigger some logic to close the ComboBox dropdown.

Tip For Finding Resources for a Control in generic.xaml

I’ve recently be working on changing the ControlTemplate of a GridViewColumnHeader in a custom ListView that we’ve been working on. (The ListView was rewritten for sorting, so that’s why it had to be custom.)

One of the things we had to do was swap out ControlTemplates so that we could display a caret to indicate ascending or descending lists. We ended up deciding on ControlTemplates over DataTemplates because the DataTemplates would only work for ListViews that had no custom DataTemplates for the headers. We’re doing all sorts of crazy stuff with our headers and we need to preserve our DataTemplates, so this wasn’t an option.

In any case, I was having no luck finding the resource when I named it this way:

<ControlTemplate x:Key="MyCustomControlTemplate" TargetType="{x:Type GridViewColumnHeader}">

I was using the following code to try and find the resource.

ControlTemplate myNewTemplate = (ControlTemplate)Resources["MyCustomTemplate"];

However, we were able to solve the problem by naming the resource this way

<ControlTemplate x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type local:MyCustomListView}, ResourceId=MyCustomControlTemplate}"
        
TargetType="{x:Type GridViewColumnHeader}">

And then using this code to access it.

ComponentResourceKey myCustomTemplateKey = new ComponentResourceKey(typeof(SortableListView), "MyCustomTemplate");
ControlTemplate myNewTemplate = (ControlTemplate)this.TryFindResource(myCustomTemplateKey);

Just thought I’d pass it along.

How to Assign ColumnHeaderContainerStyle and ColumnHeaderTemplate to a ListView Style

This is just a quick note on creating a ListView style with the appropriate GridView style and template assignments.

Normally, I’ve been creating listviews that look like this:

<ListView x:Name=”MyListView”
               ItemContainerStyle
=”{DynamicResource MyListViewItemContainerStyle}”>
   
<ListView.View>
        
<GridView ColumnHeaderContainerStyle=”{DynamicResource MyListViewHeaderStyle}”
                        
ColumnHeaderTemplate=”{DynamicResource MyGridColumnHeaderTemplate}”> 

I did this because I didn’t know exactly how to assign these styles and templates to the ListView Style. In the style, ColumnHeaderContainerStyle and ColumnHeaderTemplate are not properties of the ListView, they are properties of the GridView… which you can’t create a style for.

Instead, you can encapsulate all the information above in the following style.

<Style x:Key=”CustomListViewStyle” TargetType=”{x:Type ListView}”>
      <
Setter Property=”GridView.ColumnHeaderContainerStyle” Value=”{DynamicResource MyListViewHeaderStyle}” />
     
<Setter Property=”GridView.ColumnHeaderTemplate” Value=”{DynamicResource MyGridColumnHeaderTemplate}” />
     
<Setter Property=”ItemContainerStyle” Value=”{DynamicResource MyListViewItemContainerStyle}” />
</Style>

Problem solved.

How Do I Make a ListView or a ScrollViewer Left Handed?

Several months back, I was doing some work for a company that was using WPF for a stylus based application. One of the things that they found they needed was a scrollbar that could be used by left handed people who would have to cover the entire screen with their left hand in order to scroll a traditional scroll viewer.

The solution ended up being so easy in WPF that I thought I’d post it here.

I’m in a two-birds-one-stone mood, so we’ll do this for both the listview, which will also cover a more traditional scrollviewer. Let’s start with our ever friendly listview.

NormalListViewAt the very sight of this thing, with a stylus in hand, your average lefty is thinking to him or herself “I wonder if I can do my work upside down?” Let’s show them that we love and accept them just as they are.

The first thing we’re going to do is create a new template for this sucker, so right click on your listview and go to “Edit Control Parts (Template) -> Edit a Copy…

Lefty_EditControlParts

Now we’re looking at the standard listview template. Mine looks like this:

ListViewTemplateLet’s dig right into the ScrollViewer. If you’re doing this from the listview (like I am) then creating a template for the listview has already created a template for the scrollviewer. If you’re starting from a basic scrollviewer, you can pretty much start right here.

For the purposes of making this thing easy to work with in Blend, go ahead and set the HorizontalScrollBarVisibility and VerticalScrollBarVisibility to Visible.

 ScrollBar_Visibility

And then “Edit Control Parts (Template) -> Edit a Copy…” (or “Edit Control Parts (Template) -> Edit Template” if it is available).

We are now looking at the guts of the ScrollViewer Control.

ListView ScrollViewer will look like this:

ListViewScrollTemplateThe normal ScrollViewer will look like this:

 NormalScrollViewer

For our purposes, they’re functionally the same. It is actually a fairly simple control… basically just a Grid panel with the columns and rows set up like so:

<Grid.ColumnDefinitions>
      <ColumnDefinition Width=”*/>
      <ColumnDefinition Width=”Auto/>
</Grid.ColumnDefinitions>

<Grid.RowDefinitions>
      <RowDefinition Height=”*/>
      <RowDefinition Height=”Auto/>
</Grid.RowDefinitions>

The scrollBars are set up so that their visibility is tied to (duh) the visibility that is set on the control. But what this does is it means that when they are collapsed… they Grid reclaims the space that they were taking up.

Now… here’s the hilarious part… in order to make this ScrollViewer left handed, all you have to do is swap the Grid.Columns:

<Grid.ColumnDefinitions>
      <ColumnDefinition Width=”Auto/>
      <ColumnDefinition Width=”*/>
</Grid.ColumnDefinitions>

You’ve now switched the columns so that the left handed column is auto. Here’s a list of the Grid.Column realignments you’ll need to make:

Change Column to “1″:

Lefty_Column1

  • PART_HorizontalScrollBar
  • All DockPanels (ListView only)
  • PART_ScrollContentPresenter (ScrollViewer only)
  • Corner (ScrollViewer only)

Change Column to “0″:

Lefty_Column0

  • PART_VerticalScrollBar

Basically, swap everything from in the two columns.

Done.

FinalLeftyListViewIf you want to make this a more robust control, I recommend creating a ScrollViewer with an additional dependency property (IsSouthPaw or something). Make it so that your Grid has three columns:

<Grid.ColumnDefinitions>
      <ColumnDefinition Width=”Auto/>
      <ColumnDefinition Width=”*/>
      <ColumnDefinition Width=”Auto/>

</Grid.ColumnDefinitions>

And then you can just create a trigger that swaps the column placement of your PART_VerticalScrollBar. Such a trigger will look something like this. And by “something”, I mean “exactly”.

<Trigger Property=”IsSouthPawValue=”True>
      <Setter Property=”Grid.ColumnTargetName=”PART_VerticalScrollBar“  Value=”0/>
</Trigger>

Go forth and make Ned Flanders proud.

By the way, I listen to pop punk whenever I write my tutorials and I just thought I should let Senses Fail know that they can probably get away with about 80% less “dying cat” screaming and still put out good music. You know… because they’re probably WPF programmers on the side and they’ll probably read this to solve all their left-handed scrollbar needs.

ListView (and ListBox) Performance Issues

I was working on one of my projects today and I noticed that one of our popups displaying search results in a ListBox was having really serious performance problems.  After determining that the problem was, in fact, on the WPF side of things, I was somewhat baffled. I wasn’t doing anything that I could think of that should be pushing the limit of what WPF could do.

 Finally, I went looking online for an answer and discovered a list of possible performance killers for the ListView (and ListBox) on Mark Shurmer’s blog. Chief among his no-no’s:

Embedding the ListView inside a StackPanel

Which is exactly what I was doing.

Why is this a problem? To answer that question, let’s take a look at the ItemsPanel at runtime using Snoop. When I place my ListBox into a Grid, here is what my ItemsPanel looks like:

Continue reading ‘ListView (and ListBox) Performance Issues’ »

How Do I Wrap Text in a ListView Header?

OK, it’s really late and I want to get this done, so we’re going to go through the easy way, which will require some XAML, but I’ll try to keep it as Blend-y as possible.

So you have a column header and you want the text inside to wrap when the header space gets too short for the content. Your header probably looks something like this:

OriginalHeader

First, go to wherever your resources are being held and type the following in:

<Style x:Key=”CustomHeaderStyle“ TargetType=”{x:Type GridViewColumnHeader}>
</Style>

Continue reading ‘How Do I Wrap Text in a ListView Header?’ »

Embedded ListView Columns (Columns Within Columns)

Please Read: Strangely, when you do a Google search for “wpf” and “listview”, this is one of the top links. This is odd because this particular post is kind of an advanced tutorial. If you’re looking for more general information on styling the wpf listview, check out this post. It is probably much closer to what you’re looking for.

This is a bit of an advanced tutorial. I’m putting it up because I just figured out how to do it and I want to share. You can also download the project files for this tutorial (in zip format… requires .Net 3.5).

Recently, I received from my user experience designers a wireframe that looked something like this:

EmbeddedWireframe

As you can see, there are embedded categories (categories within categories) here. I considered many solutions (hacks), but I found that a deeper understanding of the ListView and how it works would allow me to resolve this issue very simply (and without even touching the code behind). Continue reading ‘Embedded ListView Columns (Columns Within Columns)’ »

How do I style the ListView column gripper (also known as a “splitter” or a “seperator”)

I had a question from a reader in an earlier post on how to resize the ListView Gripper (seen below) so I wanted to address that in this quick post.

GripperExample

 Styling the gripper is actually pretty easy. First, take a look at my Styling the ListView Column Header post. Follow that along until you get to the template for the ColumnHeader (by the fifth image down).

You should have something that looks like this:

Column_Header_Template

Now we’re going to ignore everything here except that little part at the bottom the “PART_HeaderGripper”

Continue reading ‘How do I style the ListView column gripper (also known as a “splitter” or a “seperator”)’ »

Styling the ListView Column Header

ListView header Styling is one of the most difficult styling pieces I’ve had to deal with. Part of this is because it is just another part of the seemingly endlessly complex listview. The other part is just because of the way the styling for the listview is put together in WPF.

In this post, we’re going to change the default color of the header (background and foreground) and make the headers look more like bubbles. Why? Because we can! (Everytime I say that, somewhere a usability expert loses a little bit of their soul.)

Take note that anything done in this will affect the whole header. If you’re looking to do something to one individual column in the header, you need to go to this post on ColumnHeaders (coming soon). See the bottom of this post for more details.

As a point of note, the easy way in this particular case involves going directly into the XAML and the hard way involves going through the steps in Blend. The easy way is posted at the bottom.

Now for the hard way. First, go to your listview, right click on it and go to:

Edit Control Parts (Template) -> Edit a Copy…

1_ControlParts
Continue reading ‘Styling the ListView Column Header’ »

Styling ListView Items Using Blend

So… you’ve got your listview and you want your items to look a certain way. In this post, we’ll look at changing as many things as we can inside the ListView ItemContainerStyle.

 First things first… getting to the ItemContainerStyle using Blend. With the ListView selected, go to the top menu and click:

 Edit Other Styles -> Edit ItemContainerStyle -> Create Empty…

ItemContainerStyleMenu

Name your Style and you get tossed into Style editing. Here, you can do all sorts of great things, like… um… changing the background or something.

Continue reading ‘Styling ListView Items Using Blend’ »

출처 : http://www.designerwpf.com/category/listview/

posted by Sunny's
2009. 3. 31. 15:20 WPF, Silverlight
프로그램이 중복 실행되는 것을 막는 가장 일반적인 방법은 Mutex를 사용하여 프로세스를 확인하는 방법입니다.
C#에서 사용되는 방법은 msdn에도 Mutex의 예제로 아래와 같이 나와 있습니다.
msdn에 나온 Mutex의 기본 사용법을 보시고 싶으신 분은 아래 소스를 펼쳐 보시면 됩니다.

하지만 WPF에서 위에 방법을 App.xaml.cs 에 적용시켜도 원하는 데로 동작하지 않습니다.
그래서 오늘은 WPF에서 사용할 수 있는 방법을 올려드리겠습니다.
아래 예제는 뮤텍스를 사용한 중복 방지 소스를 구글링해서 힘들게 찾은 소스입니다.
제가 잘 동작하는 것은 확인 하였습니다. 이 밖에 다른 예제 소스도 보여드리겠습니다만 아래 예제를 쓰시는 것이 가장 좋습니다.

01.using System;
02.using System.Threading;
03.using System.Windows; 
04.namespace WpfKorea
05.{
06.    /// <summary>
07.    /// Interaction logic for App.xaml
08.    /// </summary>
09.    public partial class App : Application
10.    {
11.        Mutex mutex = null;
12.        protected override void OnStartup(StartupEventArgs e)
13.        {            
14.            string mutexName = "wpfkorea.com";
15.            try
16.            {                
17.                mutex = new Mutex(false, mutexName);
18.            }
19.            catch (Exception ex)
20.            {
21.                MessageBox.Show(    ex.Message + "\n\n"  +   ex.StackTrace + "\n\n"  +   "Application Exiting…",   "Exception thrown");
22.                Application.Current.Shutdown();
23.            }
24.            if (mutex.WaitOne(0, false))
25.            {
26.                base.OnStartup(e);
27.            }
28.            else
29.            {
30.                MessageBox.Show("Application already startet.", "Error", MessageBoxButton.OK, MessageBoxImage.Information);
31.                Application.Current.Shutdown();
32.            }
33.        }
34.    }
35.}


위에 예제는 OnStartUp이벤트와 Mutex의 WaitOne을 이용하여 중복방지를 구현하였습니다.



그럼 이번에는 약간 다른 방법으로 구현해 보겠습니다.
이 방법은 WPF 초기화를 C# 코드로 직접 구현하는 방식입니다.

 

01.private static bool isNew;
02.[System.STAThreadAttribute()]
03.public static void Main()
04.{
05.    using (Mutex m = new Mutex(true, "ThisIsTheStringMutexValueThatMustBeUnique", out isNew))
06.    {
07.        if (isNew)
08.        {
09.            MyWPFApplication.App app = new MyWPFApplication.App();
10.            app.InitializeComponent();
11.            app.Run();
12.        }
13.        else
14.        {
15.            MessageBox.Show("MyWPFApplication is already running!", "MyWPFApplication", MessageBoxButton.OK, MessageBoxImage.Information, MessageBoxResult.OK);
16.        }
17.    }
18.}


이 방법을 사용하면 App.xaml의 Build Action 속성을 ApplicationDefinition 에서 Page로 변경해 주어야 합니다.
WPF가 구성해주는 진입점을 직접 작성하셔야 하므로 여러가지로 귀찮은 일이 생길 수 있을 거 같습니다.

마지막으로 소개해 드릴 방법은 프로세서의 네임 중복을 체크하는 방법입니다. 
이 방법은 잘 동작하지만 실행파일의 이름을 바꾸기만 해도 쉽게 중복 실행이 가능해 집니다.

01.public partial class App : Application
02.{
03.    public App() : base()
04.    {
05.        System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName);
06.        if (process.Length > 1)
07.        {
08.            MessageBox.Show("MyApplication is already running ...", "MyApplication Launch", MessageBoxButton.OK, MessageBoxImage.Information);
09.                this.Shutdown();
10.       }
11.    }
12.}

이런 방법들을 사용하시면 WPF에서 중복방지를 구현하실수 있습니다.
길게 읽지 않으시고 첫번째 소개해 드린 방법을 사용하시면 됩니다.
나머지는 참고만 하셔도 될 것 같습니다.

출처 : http://wpfkorea.com/?document_srl=3047#0

posted by Sunny's
prev 1 2 next