Calendrier

Décembre 2009
L M M J V S D
  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      
<< < > >>

Présentation

Recherche

W3C

  • Flux RSS des articles

WPF

[TechHeadBrothers] - [WPF] Le pourquoi du comment des Dependency Properties

http://www.techheadbrothers.com/articles.aspx/dependency-properties
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

Wallpaper Manager 1.0 - (WPF sample)

je cite : "The Wallpaper Manager is a Proof of Concept WPF application I built using Expression Blend and Visual Studio .NET 2008 (Codename Orcas)." 

http://blogs.msdn.com/echarran/archive/2007/08/25/wallpaper-manager-1-0.aspx

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

[WPF] - UIElement3D extensibility - 3D Video Carousel

exemple visual studio 2008 fourni

"Concepts you can see in practice with this sample include:

  • Creating interactive 3D controls as interactive containers on non-interactive 3D models (Hint - Leverage existing 3D Xaml with little effort)
  • Creating a Custom Visual3D container type
  • Use of StaticResources from Application.Resources to separate mesh details from overall structure
  • Databinding a mesh texture to consume a local DP exposed as a URI, via a data binding type converter
  • 3D Layout - Cylinder Layout Helper class
  • Playing Video as a material on 3D"
http://blogs.msdn.com/pantal/archive/2007/08/22/uielement3d-extensibility-dvd-keep-case-player-cylindrical-carousel-layout.aspx
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] - Créer des controls
en C# dans le code-behind
 
J’ai montré dans un précédent post comment on pouvait lier chaque element d’un DataTemplate à une source
Ici je vais montrer que l’on peu très bien définir à la fois la structure de chaque comboxItem et les données tout en C#,cette approche me plait bien plus que de passer par des raccourcis, car ici on contrôle d’avantage
D’ailleurs on n’est pas obligé de définir chaque comboBoxItem avec la même structure,ce qui devient interessant ..
 
public ComboBoxItem CreateContactItem(Contact contact)
        {
            // le comboBoxItem courant à ajouter
            ComboBoxItem comboBoxItem = new ComboBoxItem();
 
            // conteneur
            WrapPanel wrapPanel = new WrapPanel();
 
            // elements à inserer dans le conteneur
            BitmapImage bitmapImage = new BitmapImage(new Uri("images/Zoom.png", UriKind.Relative));
            Image image = new Image();
            image.Source = bitmapImage;
            image.Width = 30;
            image.Height = 30;
 
            TextBox ContactNameTextBox = new TextBox();
            ContactNameTextBox.Text = contact.ContactName;
            ContactNameTextBox.Width = 100;
            ContactNameTextBox.Height = 20;
 
            TextBox ContactFirstNameTextBox = new TextBox();
            ContactFirstNameTextBox.Text = contact.ContactFirstName;
            ContactFirstNameTextBox.Width = 100;
            ContactFirstNameTextBox.Height = 20;
 
            // on ajoute chaque control au conteneur
            wrapPanel.Children.Add(image);
            wrapPanel.Children.Add(ContactNameTextBox);
            wrapPanel.Children.Add(ContactFirstNameTextBox);
 
            // on définit le contenu du comboBoxItem
            comboBoxItem.Content = wrapPanel;
 
            return comboBoxItem;
        }
 
 
Utilisation
       List<Contact> Contacts = new List<Contact>();
 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
 
            Contacts.Add(new Contact(1, "romagny", "jerome"));
            Contacts.Add(new Contact(2, "Bellin", "marie"));
            Contacts.Add(new Contact(3, "Marx", "alex"));
 
            foreach (Contact contact in Contacts)
                cboDemo.Items.Add(CreateContactItem(contact));
 
        }
 
Et la partie xaml
<Window x:Class="WPFTemplates.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="400" Loaded="Window_Loaded">
 
            <Grid>
            <ComboBox Name="cboDemo" />
     
      </Grid>
</Window>
 
 
on obtient le mêm résultat qu'avec un datatemplate
wpfcontrolsenc.JPG
Ma réflexion m’amène à 2 constatations > en général avec les controls WPF on a :
-          La structure /l’apparence
-          Les données (contenu)
Mon but avec WPF est de séparer assez nettement ces 2 aspects pour rendre le développement moins compliqué qu’il ne peut sembler au début

et oui il y a un temps pour jouer avec WPF et un moment ou il faut voir comment on va pouvoir réellement utiliser la technologie et si c'est envisageable/dans quels cas ... loin d'un débat savoir si WPF va remplacer les windows forms, je dois avouer que je suis un peu inquiet vu rien que le nombre de bugs et le nombre de fois que Visual Studio a planté/fermer purement et simplement ,surtout que l'on est deja à la beta 2 de Visual Studio 2008 !!
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] - Lier chaque control d’un DataTemplate aux propriétés que chacun doit afficher

datatemplate.JPG

Le DataTemplate
Je le définis ici en ressource de la window mais il pourrait tout aussi bien etre dans un fichier resourcedictionnary ,…
-          On lie une propriété ,ici la propriété Text pour le binding(cela pourrait tout aussi bien etre la propriete Content d’un button ou la propriété Source d’une Image,…)
    <Window.Resources>
            <DataTemplate x:Key="template1">
                  <WrapPanel x:Name="wrapPanel1"> 
                        <
Image Width="30" Height="30" Source="images/Zoom.png"/>
                        <TextBox Name="txtContactName" Width="150" Height="20" Text="{Binding Path=ContactName}" />
                        <TextBox Name="txtContactFirstName" Width="150" Height="20" Text="{Binding Path=ContactFirstName}" />
                  </WrapPanel>
            </DataTemplate>
      </Window.Resources>
 
Utilisation
<ComboBox Name="cboDemo" ItemTemplate="{DynamicResource template1}" />
 
Ajout d’un element
cboDemo.Items.Add(new Contact(1, "romagny", "jerome"));
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] – Créer des controls (custom controls) « typés » en WPF
exemple avec une ComboBox

l’idée est simple,créer des controls que l’on pourra ajouter aux window désirées comme ce que l’on fait en windows forms avec les components ou les controls utilsateurs, évitant ainsi de mélanger tous les controls dans la même window/mieux séparer structurer
et bien sur définir l’apparence du control
couche businessObjects
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace WPFTypedControls
{
    public class Contact
    {
        private int _contactID;
 
        public int ContactID
        {
            get { return _contactID; }
            set { _contactID = value; }
        }
        private string _contactName;
 
        public string ContactName
        {
            get { return _contactName; }
            set { _contactName = value; }
        }
        private string _contactFirstName;
 
        public string ContactFirstName
        {
            get { return _contactFirstName; }
            set { _contactFirstName = value; }
        }
 
        public Contact()
        { }
        public Contact(int contactID, string contactName, string contactFirstName)
        {
            this.ContactID = contactID;
            this.ContactName = contactName;
            this.ContactFirstName = contactFirstName;
        }
        public override string ToString()
        {
           return "ContactID : " + this.ContactID.ToString() + " , ContactName : " + this.ContactName + " , ContactFirstName : " + this.ContactFirstName;
        }
    }
}
 
 
Custom control ContactComboBox
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace WPFTypedControls
{
    public class ContactComboBox : ComboBox
    {
        static ContactComboBox()
        {
            // retirer
            //DefaultStyleKeyProperty.OverrideMetadata(typeof(ContactComboBox), new FrameworkPropertyMetadata(typeof(ContactComboBox)));
        }
 
        public void AddContacts(List<Contact> contacts)
        {
            this.Items.Clear();
            foreach (Contact c in contacts)
                this.Items.Add(new ContactItem(c));
 
            if (this.Items.Count > 0)
                this.SelectedIndex = 0;         
        }
        public Contact GetContact()
        {
            ContactItem contactItem = this.SelectedItem as ContactItem;
            return new Contact(contactItem.ContactID, contactItem.ContactName, contactItem.ContactFirstName);
        }
    }
    public class ContactItem
    {
        private int _contactID;
 
        public int ContactID
       {
            get { return _contactID; }
            set { _contactID = value; }
        }
        private string _contactName;
 
        public string ContactName
        {
            get { return _contactName; }
            set { _contactName = value; }
        }
        private string _contactFirstName;
 
        public string ContactFirstName
        {
            get { return _contactFirstName; }
            set { _contactFirstName = value; }
        }
 
        public ContactItem()
        { }
        public ContactItem(Contact contact)
        {
            this.ContactID = contact.ContactID;
            this.ContactName = contact.ContactName;
            this.ContactFirstName = contact.ContactFirstName;
        }
        // la valeur affichée dans la combobox
        public override string ToString()
        {
            return this.ContactName;
        }
    }
}
 
Utilisation du custom control dans la window
Il faut ajouter un namespace (diffère selon que le custom control est dans le même projet ou non)
Celui-ci est indiqué en aide(commentaire) lors de la création du custom control
<Window x:Class="WPFTypedControls.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ContactControls="clr-namespace:WPFTypedControls"
    Title="Window1" Height="300" Width="400" Loaded="Window_Loaded">
      <Window.Resources>
            <Style x:Key="BackgroundStyle1">
                  <Setter Property="Button.Background" Value="Orange"/>
            </Style>
      </Window.Resources>
      <WrapPanel>
            <ContactControls:ContactComboBox x:Name="contactComboBox1" Height="25" Width="150" />
            <Button Name="btnGetContact" Width="170" Height="25" Content="Obtenir le contact selectionné" Click="btnGetContact_Click"/>
      </WrapPanel>
</Window>
 
Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
namespace WPFTypedControls
{
    ///<summary>
    /// Interaction logic for Window1.xaml
    ///</summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
       }
 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List<Contact> result = new List<Contact>();
            result.Add(new Contact(1, "romagny", "jerome"));
            result.Add(new Contact(2, "Bellin", "marie"));
            result.Add(new Contact(3, "Marx", "alex"));
 
            contactComboBox1.AddContacts(result);
 
        }
 
        private void btnGetContact_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(contactComboBox1.GetContact().ToString());
        }
    }
}
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] –
rendre une resource (style-template) accessible à toute l’application
1 – Ajouter un fichier de resources
resourcedictironnary.JPG

2 - On définit un style dans le fichier de ressource
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Style x:Key="BackgroundStyle1">
            <Setter Property="Button.Background" Value="Orange"/>
      </Style>
</ResourceDictionary>
 
3 – App.xaml
-          Source : Donner le chemin relatif vers le fichier de ressources
<Application x:Class="WPFTypedControls.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml">
    <Application.Resources>
         <ResourceDictionary Source="StylesDictionary.xaml"/>
     </Application.Resources>
</Application>
 
 
4 – utilisation
Dans le Xaml
<Window x:Class="WPFTypedControls.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ContactControls="clr-namespace:WPFTypedControls"
    xmlns:MyNamespace="clr-namespace:WPFTypedControls"
    Title="Window1" Height="300" Width="400" Loaded="Window_Loaded">
      <WrapPanel>
            <ContactControls:ContactComboBox x:Name="contactComboBox1" Height="25" Width="150" />
            <Button Name="btnGetContact" Width="170" Height="25" Content="Obtenir le contact selectionné" Click="btnGetContact_Click" Style="{StaticResource BackgroundStyle1}"/>
      </WrapPanel>
</Window>
 
Dans le code-behind (C#)
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
 
            btnGetContact.Style = (Style)(Application.Current.Resources["BackgroundStyle1"]);
        }
 
    }
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] –
Accèder à une resource de la window dans le code Behind

Soit un style tout simple défini dans les ressources de la Window que je vais affecter au background d’un button
<Window x:Class="WPFTypedControls.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="400" Loaded="Window_Loaded">
      <Window.Resources>
            <Style x:Key="BackgroundStyle1">
                  <Setter Property="Button.Background" Value="Orange"/>
            </Style>
      </Window.Resources>
      <WrapPanel>      
            <Button Name="btnGetContact" Width="170" Height="25" Content="Obtenir le contact selectionné" Click="btnGetContact_Click"/>
      </WrapPanel>
</Window>
 
2 possibilités pour affecter ce style :
-          Dans le Xaml
 
            <Button Name="btnGetContact" Width="170" Height="25" Content="Obtenir le contact selectionné" Click="btnGetContact_Click" Style="{StaticResource BackgroundStyle1}"/>
 
-          Dans le code-behind
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
 
            btnGetContact.Style = (Style)(this.Resources["BackgroundStyle1"]);
        }
}
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Les animations WPF - introduction
 
<Conteneur.Triggers>
<!--EventTrigger RoutedEvent="evenement declenchant l'animation"-->          
          <EventTrigger RoutedEvent="Button.Click">
           <!-- BeginStoryboard-->
            <BeginStoryboard>
              <Storyboard>
             
              <!-- Type d'animation
              Storyboard.TargetName="nom de element visé"
              Storyboard.TargetProperty="la propriété de l'élement visé à modifier"
              From="valeur départ" To="valeur fin"
              Duration="durée s'ecoulant entre valeur début et fin"
              -->
 
             
              </Storyboard>
            </BeginStoryboard>
          </EventTrigger>
</Conteneur.Triggers>
I – En resource
Mettre en resource :
<!-- 1 Les resources-->
      <Window.Resources>
      <!-- Storyboard x:Key="Nom appelé par l'EventTrigger" -->
            <Storyboard x:Key="OnClick1">
            <!-- Animation désirée -->
                  <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="button1" Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
                        <SplineColorKeyFrame KeyTime="00:00:05" Value="#FFA1A126"/>
                  </ColorAnimationUsingKeyFrames>
                 
            </Storyboard>
      </Window.Resources>
      <!-- 2 les Triggers -->
      <Window.Triggers>
      <!--EventTrigger RoutedEvent="evenement visé" SourceName="nom de l'élément visé" -->
            <EventTrigger RoutedEvent="ButtonBase.Click" SourceName="button1">
                  <BeginStoryboard Storyboard="{StaticResource OnClick1}"/>
            </EventTrigger>
      </Window.Triggers>
Utilisation :
<Button x:Name="button1" Width="250" Height="50" Content="OK"/>
 
II - Dans le control lui-même
<!-- 1 . -->
      <Button x:Name="button1" Width="250" Height="50" Content="OK">      
      
       <!-- 2 les Triggers du control-->
       <Button.Triggers> 
       <!--EventTrigger RoutedEvent="evenement declenchant l'animation"-->        
          <EventTrigger RoutedEvent="ButtonBase.Click">
           <!-- BeginStoryboard-->
            <BeginStoryboard>
              <Storyboard>
             
                <!-- Animation désirée -->
                  <ColorAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="button1"   Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
                        <SplineColorKeyFrame KeyTime="00:00:05" Value="#FFA1A126"/>
                  </ColorAnimationUsingKeyFrames>
              </Storyboard>
            </BeginStoryboard>
          </EventTrigger>        
        </Button.Triggers>
 
        </Button>
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

System.Windows.Media.Animation Namespace 

Le namespace permettant d'animer ses objets WPF

http://msdn2.microsoft.com/en-us/library/system.windows.media.animation.aspx

 

System.Linq

toutes les méthodes sur MSDN

http://msdn2.microsoft.com/en-us/library/system.linq.enumerable_members(VS.90).aspx

 

on peut également tout simplement ouvrir l'assembly System.Core.dll qui se trouve  dans

C://Program Files//Reference Assemblies//Microsoft//Framework//v3.5

avec Reflector

Linq1.JPG

 

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

De Windows Form à WPF

un nouveau Webcast (mercredis du développements - Mitzu Furuta) qu'il faut que je m'empresse de suivre :p

http://www.microsoft.com/france/msdn/evenements/mercredis_developpement/windows-form-wpf.mspx

  + rappel

le site sur .NET 3.0 qui regorge de ressources :)

http://www.netfxfactory.org/

 

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] - Les transformations
I - transformations simples
Une seule transformation appliquée
1 – RotateTransform : tourne
      <!-- RotateTransform Tourne le control- de l'angle spécifié -->
      <Button Content="OK" Width="120" Height="20">
        <Button.RenderTransform>
          <RotateTransform Angle="90"/>
        </Button.RenderTransform>
      </Button>
 
  t1.JPG
2 – ScaleTransform : modifie l’ echelle/taille
      <!-- ScaleTransform : modification d'echelle (ex : si ScaleX="2" alors la longueur du control est multipliée par 2) -->
      <Button Content="OK" Width="120" Height="20">
        <Button.RenderTransform>
          <ScaleTransform ScaleX="2" ScaleY="2" />
        </Button.RenderTransform>
      </Button>
 
  t2.JPG
3 – SkewTransform : met en oblique
<!-- SkewTransform : met en oblique le control -->
      <Button Content="OK" Width="120" Height="20">
        <Button.RenderTransform>
          <SkewTransform AngleX="45" AngleY="0" />
        </Button.RenderTransform>
      </Button>
 
  t3.JPG
4 – TranslateTransform : deplace sur axe x et y
<!-- TranslateTransform : deplace le control sur axe x et y-->
      <Button Content="OK" Width="120" Height="20">
        <Button.RenderTransform>
          <TranslateTransform X="-80" Y="0" />
        </Button.RenderTransform>
      </Button>
 
  t4.JPG
5 - Les transformations peuvent s’appliquer à
<!-- Brush -->
      <Rectangle>
        <Rectangle.Fill>
          <ImageBrush ImageSource="C:Documents and SettingsromagnyMes documentsMes imagesanna47[1].jpg">
            <ImageBrush.Transform>
              <RotateTransform Angle="45" />
            </ImageBrush.Transform>
          </ImageBrush>
        </Rectangle.Fill>
      </Rectangle>
 
<!-- DrawingGroup -->
      <Image>
        <Image.Source>
          <DrawingImage>
            <DrawingImage.Drawing>
 
              <DrawingGroup>
                <GeometryDrawing Brush="Yellow" Geometry="M 25,25 L 0,50 25,75 50,50 25,25 25,0">
                  <GeometryDrawing.Pen>
                    <Pen Thickness="10" Brush="Black" />
                  </GeometryDrawing.Pen>
                </GeometryDrawing>
              
                <DrawingGroup.Transform>
                  <RotateTransform Angle="45" />
                </DrawingGroup.Transform>
 
              </DrawingGroup>
            </DrawingImage.Drawing>
          </DrawingImage>
        </Image.Source>
      </Image>
<!-- Geometry -->
      <Path Stroke="Black" Fill="Yellow">
        <Path.Data>
          <GeometryGroup>
            <RectangleGeometry Rect="30,55 100 30" />
 
            <GeometryGroup.Transform>
              <RotateTransform Angle="45" />
            </GeometryGroup.Transform>
           
          </GeometryGroup>
        </Path.Data>
      </Path>
 
<!-- TextEffect -->
      <TextBlock Text="un texte" Width="120" Height="20">
        <TextBlock.TextEffects>
          <TextEffect PositionCount="10">
            <TextEffect.Transform>
              <RotateTransform Angle="45"/>
            </TextEffect.Transform>
          </TextEffect>
        </TextBlock.TextEffects>
      </TextBlock>
 
 
+ tous les controls (FrameworkElement),UIElement,ContainerVisual
 
II - Des transformations complexes
 appliquer plusieurs transformations au lieu d’une seule
1 - TransformGroup
 <!-- TransformGroup : permet appliquer plusieurs transformations au lieu d'une seule au control-->
<Button Content="OK" Width="120" Height="20">
        <Button.RenderTransform>
          <TransformGroup>
            <RotateTransform Angle="90"/>
            <ScaleTransform ScaleX="2" ScaleY="2" />
          </TransformGroup>
        </Button.RenderTransform>
      </Button>
 
t5.JPG  
2 – MatrixTransform : utiliser une matrice
<Button Content="OK" Width="120" Height="20">
        <Button.RenderTransform>
          <MatrixTransform x:Name="myMatrixTransform">
            <MatrixTransform.Matrix >
              <Matrix OffsetX="-10" OffsetY="-20" M11="1" M12="1" M21="5" M22="2"/>
            </MatrixTransform.Matrix>
          </MatrixTransform>
        </Button.RenderTransform>
      </Button>
 
  t6.JPG
 
III - Créer une animation basée sur une transformation
<Button Content="Valider" RenderTransformOrigin="0.5,0.5" Width="120" Height="20">
       
        <Button.RenderTransform>
          <RotateTransform x:Name="RotateTransform1" Angle="0" />
        </Button.RenderTransform>
       
        <Button.Triggers>
          <EventTrigger RoutedEvent="Mouse.MouseEnter" >
            <EventTrigger.Actions>
              <BeginStoryboard>
                <Storyboard>
                  <!-- on modifie la propriete Angle de la transformation RotateTransform1
                  de manière à créer une animation (le bouton tourne au survol de la souris puis revient si la souris quitte la zone du button)
                  -->
                  <DoubleAnimation Storyboard.TargetName="RotateTransform1"
                    Storyboard.TargetProperty="Angle" To="360" Duration="0:0:1"/>
                </Storyboard>
              </BeginStoryboard>
            </EventTrigger.Actions>
          </EventTrigger>
          <EventTrigger RoutedEvent="Mouse.MouseLeave" >
            <EventTrigger.Actions>
              <BeginStoryboard>
                <Storyboard>
                  <!-- on modifie la propriete Angle de la transformation RotateTransform1
                  de manière à créer une animation (le bouton tourne puis revient)
                  -->
                  <DoubleAnimation Storyboard.TargetName="RotateTransform1"
                    Storyboard.TargetProperty="Angle" To="0" Duration="0:0:1"/>
                </Storyboard>
              </BeginStoryboard>
            </EventTrigger.Actions>
          </EventTrigger>
        </Button.Triggers>
       
      </Button>
 
 
 
Lien
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
[WPF] - Accéder aux controls directement sans passer par le binding
 
Soit :
Ici j’ai une TextBox qui a un Template simpliste pour bien comprendre
(Le template comprend donc une grille avec une TextBox, mais on pourrait facilement ajouter par exemple une image et d’autres controls)
<Window x:Class="WPFFindNameAndVisualTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPFFindNameAndVisualTest" Height="300" Width="300"
    >
 <StackPanel Name="StackPanel1">
    <Button Name="btnTestFindName" Click="btnTestFindName_Click" Height="23"   Width="75">Test FindName()</Button>
    <TextBox Name="txtTestFindName" Width="150" Height="20"/>
 
    <Separator/>
   
    <Button Name="btnTestVisual" Click="btnTestVisual_Click" Height="23"   Width="75">Test Visual</Button>
    <TextBox Name="txtTemplate">
      <TextBox.Template>
        <ControlTemplate >
          <Grid ShowGridLines="Truex:Name="Grid1">
            <TextBox Name="txtTestVisual" Width="150" Height="20" />
          </Grid>
        </ControlTemplate>
      </TextBox.Template>
    </TextBox>
 </StackPanel>
</Window>
 
1 - FrameworkElement.FindName()
Il faut que l’élément soit declaré côté window.g.cs pour réussir à le trouver
public void btnTestFindName_Click(object e, RoutedEventArgs args)
        {
 
            object wantedNode = StackPanel1.FindName("txtTestFindName");
            if (wantedNode is TextBox)
            {
                TextBox wantedChild = wantedNode as TextBox;
                wantedChild.Text = "trouvé";
 
            }
        }
 
Window1.g.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     Ce code a été généré par un outil.
//     Version du runtime :2.0.50727.42
//
//     Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si
//     le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
 
using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
 
 
namespace WPFFindNameAndVisualTest {
   
   
    ///<summary>
    /// Window1
    ///</summary>
    public partial class Window1 : System.Windows.Window, System.Windows.Markup.IComponentConnector {
       
        internal System.Windows.Controls.StackPanel StackPanel1;
       
        internal System.Windows.Controls.Button btnTestFindName;
       
        internal System.Windows.Controls.TextBox txtTestFindName;
       
        internal System.Windows.Controls.Button btnTestVisual;
       
        internal System.Windows.Controls.TextBox txtTemplate;
       
        private bool _contentLoaded;
       
        ///<summary>
        /// InitializeComponent
        ///</summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/WPFFindNameAndVisualTest;component/window1.xaml", System.UriKind.Relative);
            System.Windows.Application.LoadComponent(this, resourceLocater);
        }
       
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
            switch (connectionId)
            {
            case 1:
            this.StackPanel1 = ((System.Windows.Controls.StackPanel)(target));
            return;
            case 2:
            this.btnTestFindName = ((System.Windows.Controls.Button)(target));
           
            #line 7 "....Window1.xaml"
            this.btnTestFindName.Click += new System.Windows.RoutedEventHandler(this.btnTestFindName_Click);
           
            #line default
            #line hidden
            return;
            case 3:
            this.txtTestFindName = ((System.Windows.Controls.TextBox)(target));
            return;
            case 4:
            this.btnTestVisual = ((System.Windows.Controls.Button)(target));
           
            #line 12 "....Window1.xaml"
            this.btnTestVisual.Click += new System.Windows.RoutedEventHandler(this.btnTestVisual_Click);
           
            #line default
            #line hidden
            return;
            case 5:
            this.txtTemplate = ((System.Windows.Controls.TextBox)(target));
            return;
            }
            this._contentLoaded = true;
        }
    }
}
 
 
2 – FrameworkTemplate.FindName()
 
Permet acceder aux controls d’un template
Donc dans mon cas cela donnerait par exemple pour accéder à la TextBox txtTestVisual :
public void btnTestFindName_Click(object e, RoutedEventArgs args)
        {
            Grid grid = this.txtTemplate.Template.FindName("Grid1", this.txtTemplate) as Grid;
 
            TextBox oTextBox = grid.FindName("txtTestVisual") as TextBox;
            oTextBox.Text = "trouvé grâce à FrameworkTemplate.FindName()";
 
        }
> Thomas Lebrun explique trés bien cela sur son blog
[WPF] Comment accéder aux contrôles existants dans un Template ?
3 – VisualTreeHelper
Permet accéder aux tous controls même ceux d’un template
public void btnTestVisual_Click(object e, RoutedEventArgs args)
        {
            EnumVisual(txtTemplate);
        }
 
        public void EnumVisual(Visual oVisual)
        {
            for (int nVisualChildrenCount = 0; nVisualChildrenCount < VisualTreeHelper.GetChildrenCount(oVisual); nVisualChildrenCount++)
            {
                Visual childVisual;
 
                childVisual = (Visual)VisualTreeHelper.GetChild(oVisual, nVisualChildrenCount);
 
                if (childVisual is TextBox)
                {
                    TextBox wantedChild = childVisual as TextBox;
                    //
                    if (wantedChild.Name == "txtTestVisual")
                    {
                        wantedChild.Text = "trouvé";
                    }
 
                }
 
                //
                EnumVisual(childVisual);
            }
        }
 
 
Liens
FrameworkElement.FindName Method
 
VisualTreeHelper Class 
 
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
WPF – Créer un texte dégradé
 
Ici par exemple avec un dégradé linéaire
<Window x:Class="NET3CSButton.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NET3CSButton" Height="300" Width="367"
    >
 <Grid>
 
    <Grid.Resources>
      <Style TargetType="{x:Type TextBlock}">
        <Setter Property = "Foreground">
          <Setter.Value>
            <LinearGradientBrush>
              <GradientStop Color="Yellow" Offset="0.0" />
              <GradientStop Color="Red" Offset="0.5" />
              <GradientStop Color="Blue" Offset="1.0" />
            </LinearGradientBrush>
          </Setter.Value>
        </Setter>
      </Style>
    </Grid.Resources>
 
    <Grid.ColumnDefinitions>
      <ColumnDefinition></ColumnDefinition>
      <ColumnDefinition Width="250" ></ColumnDefinition>
      <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
   
    <TextBlock Width="200" Height="50" Grid.Column="1" Grid.Row="1" Text="Joli dégradé" FontSize="20">
   
    </TextBlock>
 </Grid>
</Window>
 
 
 
On peut également utiliser une image en fond
<Window x:Class="NET3CSButton.Window2"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NET3CSButton" Height="300" Width="367"
    >
 <Grid>
    <Grid.Resources>
      <Style TargetType="{x:Type TextBlock}">
        <Setter Property = "Foreground">
          <Setter.Value>
            <ImageBrush ImageSource="C:Documents and SettingsromagnyMes documentsMes imagesciel.jpg" />
          </Setter.Value>
        </Setter>
      </Style>
    </Grid.Resources>
 
    <Grid.ColumnDefinitions>
      <ColumnDefinition></ColumnDefinition>
      <ColumnDefinition Width="250" ></ColumnDefinition>
      <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
      <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>
   
    <TextBlock Width="200" Height="50" Grid.Column="1" Grid.Row="1" Text="Joli dégradé" FontSize="20">
   
    </TextBlock>
 </Grid>
</Window>
 
 
  img5.JPG
Lien MSDN
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
WPF – utiliser les BitmapEffects
1 – Quelques exemples d’effets
a-BevelBitmapEffect (relief et lumière)
<Grid.BitmapEffect>
     <BevelBitmapEffect BevelWidth="10" LightAngle="50" Relief="1"/>
</Grid.BitmapEffect>
 
img1.JPG
b-DropShadowBitmapEffect (ombre)
<Grid.BitmapEffect>
    <DropShadowBitmapEffect Color="Red" Direction="20" Opacity="0.9" Softness="1" />
</Grid.BitmapEffect>
 
img2.JPG  
C - OuterGlowBitmapEffect (contour)
 
<Grid.BitmapEffect>
    <OuterGlowBitmapEffect GlowColor="Red" GlowSize="10" />
</Grid.BitmapEffect>
 
img3.JPG
 
2 - Créer un effet  suite à un événement
Exemple : au survol d’un bouton par la souris
<Window x:Class="NET3CSButton.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NET3CSButton" Height="300" Width="300"
    >
 <Grid>
 
    <Grid.Resources>
      <Style TargetType="{x:Type Button}">
        <Style.Triggers>
          <Trigger  Property="IsMouseOver" Value="True">
            <Setter Property = "BitmapEffect" >
              <Setter.Value>
                <OuterGlowBitmapEffect GlowColor="Red" GlowSize="10" />
              </Setter.Value>
            </Setter>
          </Trigger>
        </Style.Triggers>
      </Style>
    </Grid.Resources>
 
    <Button Name="btnValidate" Width="150" Height="20" Content="OK" />
 
 </Grid>
</Window>
 
 
img4.JPG
On peut également créer une animationavec EventTrigger
<Window x:Class="NET3CSButton.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NET3CSButton" Height="300" Width="300"
    >
 <Grid>
 
    <Button Name="btnValidate" Width="150" Height="20" Content="OK">
    
 <Button.BitmapEffect>
        <OuterGlowBitmapEffect x:Name="OuterGlowBitmapEffect1" GlowColor="Red" GlowSize="0" />
      </Button.BitmapEffect>
 
      <Button.Triggers>
        <EventTrigger RoutedEvent="Mouse.MouseEnter">
          <EventTrigger.Actions>
            <BeginStoryboard>
              <Storyboard>
                <DoubleAnimation
                  Storyboard.TargetName="OuterGlowBitmapEffect1"
                  Storyboard.TargetProperty="GlowSize"
                  From="0" To="40" Duration="0:0:0.5" />
              </Storyboard>
            </BeginStoryboard>
          </EventTrigger.Actions>
        </EventTrigger>
      </Button.Triggers>
 
    </Button>
 </Grid>
</Window>
 
 
Liens
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

UniVRSS

Un RSS Reader en WPF et tout en 3D

les sources sont également disponibles

http://www.microsoft.com/emea/msdn/thepanel/en/featured/universs.aspx

  rssredaer.JPG

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

Tech Head Brothers - Article WPF

un petit article interessant sur WPF

http://www.techheadbrothers.com/Articles.aspx?Id=e7447ad5-cd88-405d-86ea-084bf2c667ae&p=1

 

Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander
Par Romagny13
- Voir les commentaires - Recommander
Utilisation des  thèmes prédéfinis avec WPF
I – Aero
1 – référencer PresentationFramework.Aero
2 – Ajouter en resource (les styles seront appliqués à tous les controls du conteneur)
Normalcolor uniquement (Thème Windows Vista)
    <Window.Resources>
      <ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/Aero.normalcolor.xaml" />
    </Window.Resources>
 
II - Luna
1 – référencer PresentationFramework.Luna
2 – Ajouter en resource (les styles seront appliqués à tous les controls du conteneur)
a-Normalcolor (Thème Bleu Windows XP )
   <Window.Resources>
      <ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/Luna.normalcolor.xaml" />
    </Window.Resources>
 
b-Homestead (Thème Marron clair Windows XP)
   <Window.Resources>
      <ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/Luna.homestead.xaml" />
    </Window.Resources>
 
c-Metallic (Thème Argenté Windows XP)
   <Window.Resources>
      <ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/Luna.metallic.xaml" />
    </Window.Resources>
 
III – Royale
1 – référencer PresentationFramework.Royale
2 – Ajouter en resource (les styles seront appliqués à tous les controls du conteneur)
Normalcolor uniquement
    <Window.Resources>
      <ResourceDictionary Source="/PresentationFramework.Royale, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/Royale.normalcolor.xaml" />
    </Window.Resources>
 
Note : cette notion est importante le thème n’est appliqué qu’au conteneur pour lequel il est mis en resource :
-          Si le thème est défini en ressource de la window, alors le thème sera appliqué à tous les controls de la form
-          on peut avoir également par exemple un wrappanel qui aurait le thème Aero et un autre conteneur le thème Luna
 
 
Par Romagny13
Ecrire un commentaire - Voir les commentaires - Recommander

Mitzu Furuta - WPF book control

Je relaie une info que j'ai vue, mais cela vaut le coup d'oeil

Mitzu Furuta présente son WPF book control et les sources sont même disponibles

http://blogs.msdn.com/mitsu/archive/2007/04/18/wpf-book-control.aspx?CommentPosted=true#commentmessage

Par Romagny13
- Voir les commentaires - Recommander
Créer un blog sur over-blog.com - Contact - C.G.U. - Rémunération en droits d'auteur - Signaler un abus