Exporter (0) Imprimer
Développer tout

DrawListViewSubItemEventArgs, classe

Remarque : cette classe est nouvelle dans le .NET Framework version 2.0.

Fournit des données pour l'événement ListView.DrawSubItem.

Espace de noms : System.Windows.Forms
Assembly : System.Windows.Forms (dans system.windows.forms.dll)

public class DrawListViewSubItemEventArgs : EventArgs
public class DrawListViewSubItemEventArgs extends EventArgs
public class DrawListViewSubItemEventArgs extends EventArgs

L'événement ListView.DrawSubItem vous permet de personnaliser (ou owner-draw) l'apparence d'un contrôle ListView en mode Détails.

L'événement ListView.DrawSubItem est déclenché par un contrôle ListView lorsque sa propriété ListView.OwnerDraw a la valeur true et sa propriété View a la valeur Details. Le DrawListViewSubItemEventArgs passé au gestionnaire d'événements contient des informations sur le ListViewItem.ListViewSubItem à dessiner et fournit également des méthodes pour vous aider à dessiner le sous-élément.

Utilisez les propriétés ItemState ou Item pour récupérer des informations sur l'élément parent du sous-élément à dessiner. Pour récupérer ListViewItem.ListViewSubItem lui-même, utilisez la propriété SubItem. Utilisez la propriété Header pour récupérer le ColumnHeader représentant l'en-tête de la colonne dans laquelle le sous-élément est affiché.

Utilisez la propriété Graphics pour réaliser le dessin proprement dit dans la zone spécifiée par la propriété Bounds. Pour dessiner des éléments ListView standard qui n'ont pas besoin de personnalisation, utilisez les méthodes DrawBackground, DrawText et DrawFocusRectangle.

Utilisez la propriété DrawDefault lorsque vous souhaitez que le système d'exploitation dessine le sous-élément. Cette opération est utile lorsque vous souhaitez personnaliser uniquement des sous-éléments spécifiques.

RemarqueRemarque

Pour éviter les problèmes de scintillement des graphiques lors du dessin owner-drawn, substituez le contrôle ListView et affectez la valeur true à la propriété DoubleBuffered. Cette fonctionnalité est uniquement disponible sur Windows XP et la famille Windows Server 2003 lorsque votre application appelle la méthode Application.EnableVisualStyles.

L'exemple de code suivant montre comment fournir un dessin personnalisé pour un contrôle ListView. Le contrôle ListView de l'exemple a un arrière-plan dégradé. Les sous-éléments de valeur négative ont une couleur de premier plan rouge et une couleur d'arrière-plan noire.

Un gestionnaire pour l'événement ListView.DrawItem dessine l'arrière-plan des éléments entiers. Un gestionnaire pour l'événement ListView.DrawSubItem dessine les valeurs texte, et à la fois le texte et l'arrière-plan des sous-éléments qui ont des valeurs négatives. Un gestionnaire pour l'événement DrawColumnHeader dessine chaque en-tête de colonne.

Un composant ContextMenu offre un moyen de basculer entre le mode Détails et le mode Liste. En mode Liste, seul l'événement ListView.DrawItem est déclenché. Dans ce cas, le texte et l'arrière-plan sont tous deux dessinés dans le gestionnaire d'événements ListView.DrawItem.

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Globalization;
using System.Windows.Forms;

public class ListViewOwnerDraw : Form
{
    private ListView listView1 = new ListView();
    private ContextMenu contextMenu1 = new ContextMenu();

    public ListViewOwnerDraw()
    {
        // Initialize the ListView control.
        listView1.BackColor = Color.Black;
        listView1.ForeColor = Color.White;
        listView1.Dock = DockStyle.Fill;
        listView1.View = View.Details;
        listView1.FullRowSelect = true;

        // Add columns to the ListView control.
        listView1.Columns.Add("Name", 72, HorizontalAlignment.Center);
        listView1.Columns.Add("First", 72, HorizontalAlignment.Center);
        listView1.Columns.Add("Second", 72, HorizontalAlignment.Center);
        listView1.Columns.Add("Third", 72, HorizontalAlignment.Center);

        // Create items and add them to the ListView control.
        ListViewItem listViewItem1 = new ListViewItem(new string[] { "One", "20", "30", "-40" }, -1);
        ListViewItem listViewItem2 = new ListViewItem(new string[] { "Two", "-250", "145", "37" }, -1);
        ListViewItem listViewItem3 = new ListViewItem(new string[] { "Three", "200", "800", "-1,001" }, -1);
        ListViewItem listViewItem4 = new ListViewItem(new string[] { "Four", "not available", "-2", "100" }, -1);
        listView1.Items.AddRange(new ListViewItem[] { listViewItem1, listViewItem2, listViewItem3, listViewItem4 });

        // Initialize the shortcut menu and 
        // assign it to the ListView control.
        contextMenu1.MenuItems.Add("List",
            new EventHandler(menuItemList_Click));
        contextMenu1.MenuItems.Add("Details",
            new EventHandler(menuItemDetails_Click));
        listView1.ContextMenu = contextMenu1;

        // Configure the ListView control for owner-draw and add 
        // handlers for the owner-draw events.
        listView1.OwnerDraw = true;
        listView1.DrawItem += new
            DrawListViewItemEventHandler(listView1_DrawItem);
        listView1.DrawSubItem += new
            DrawListViewSubItemEventHandler(listView1_DrawSubItem);
        listView1.DrawColumnHeader += new
            DrawListViewColumnHeaderEventHandler(listView1_DrawColumnHeader);

        // Add a handler for the MouseMove event to compensate for an 
        // extra DrawItem event that occurs the first time the mouse 
        // moves over each row. 
        listView1.MouseMove += new MouseEventHandler(listView1_MouseMove);

        // Add a handler for the MouseUp event so an item can be 
        // selected by clicking anywhere along its width.
        listView1.MouseUp += new MouseEventHandler(listView1_MouseUp);

        // Initialize the form and add the ListView control to it.
        this.ClientSize = new Size(292, 79);
        this.FormBorderStyle = FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.Text = "ListView OwnerDraw Example";
        this.Controls.Add(listView1);
    }

    // Clean up any resources being used.        
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            contextMenu1.Dispose();
        }
        base.Dispose(disposing);
    }

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.Run(new ListViewOwnerDraw());
    }

    // Sets the ListView control to the List view.
    private void menuItemList_Click(object sender, EventArgs e)
    {
        listView1.View = View.List;
        listView1.Invalidate();
    }

    // Sets the ListView control to the Details view.
    private void menuItemDetails_Click(object sender, EventArgs e)
    {
        listView1.View = View.Details;

        // Reset the tag on each item to re-enable the workaround in
        // the MouseMove event handler.
        foreach (ListViewItem item in listView1.Items)
        {
            item.Tag = null;
        }
    }

    // Selects and focuses an item when it is clicked anywhere along 
    // its width. The click must normally be on the parent item text.
    private void listView1_MouseUp(object sender, MouseEventArgs e)
    {
        ListViewItem clickedItem = listView1.GetItemAt(5, e.Y);
        if (clickedItem != null)
        {
            clickedItem.Selected = true;
            clickedItem.Focused = true;
        }
    }

    // Draws the backgrounds for entire ListView items.
    private void listView1_DrawItem(object sender,
        DrawListViewItemEventArgs e)
    {
        if ((e.State & ListViewItemStates.Selected) != 0)
        {
            // Draw the background and focus rectangle for a selected item.
            e.Graphics.FillRectangle(Brushes.Maroon, e.Bounds);
            e.DrawFocusRectangle();
        }
        else
        {
            // Draw the background for an unselected item.
            using (LinearGradientBrush brush =
                new LinearGradientBrush(e.Bounds, Color.Orange,
                Color.Maroon, LinearGradientMode.Horizontal))
            {
                e.Graphics.FillRectangle(brush, e.Bounds);
            }
        }

        // Draw the item text for views other than the Details view.
        if (listView1.View != View.Details)
        {
            e.DrawText();
        }
    }

    // Draws subitem text and applies content-based formatting.
    private void listView1_DrawSubItem(object sender,
        DrawListViewSubItemEventArgs e)
    {
        TextFormatFlags flags = TextFormatFlags.Left;

        using (StringFormat sf = new StringFormat())
        {
            // Store the column text alignment, letting it default
            // to Left if it has not been set to Center or Right.
            switch (e.Header.TextAlign)
            {
                case HorizontalAlignment.Center:
                    sf.Alignment = StringAlignment.Center;
                    flags = TextFormatFlags.HorizontalCenter;
                    break;
                case HorizontalAlignment.Right:
                    sf.Alignment = StringAlignment.Far;
                    flags = TextFormatFlags.Right;
                    break;
            }

            // Draw the text and background for a subitem with a 
            // negative value. 
            double subItemValue;
            if (e.ColumnIndex > 0 && Double.TryParse(
                e.SubItem.Text, NumberStyles.Currency,
                NumberFormatInfo.CurrentInfo, out subItemValue) &&
                subItemValue < 0)
            {
                // Unless the item is selected, draw the standard 
                // background to make it stand out from the gradient.
                if ((e.ItemState & ListViewItemStates.Selected) == 0)
                {
                    e.DrawBackground();
                }

                // Draw the subitem text in red to highlight it. 
                e.Graphics.DrawString(e.SubItem.Text,
                    listView1.Font, Brushes.Red, e.Bounds, sf);

                return;
            }

            // Draw normal text for a subitem with a nonnegative 
            // or nonnumerical value.
            e.DrawText(flags);
        }
    }

    // Draws column headers.
    private void listView1_DrawColumnHeader(object sender,
        DrawListViewColumnHeaderEventArgs e)
    {
        using (StringFormat sf = new StringFormat())
        {
            // Store the column text alignment, letting it default
            // to Left if it has not been set to Center or Right.
            switch (e.Header.TextAlign)
            {
                case HorizontalAlignment.Center:
                    sf.Alignment = StringAlignment.Center;
                    break;
                case HorizontalAlignment.Right:
                    sf.Alignment = StringAlignment.Far;
                    break;
            }

            // Draw the standard header background.
            e.DrawBackground();

            // Draw the header text.
            using (Font headerFont =
                        new Font("Helvetica", 10, FontStyle.Bold))
            {
                e.Graphics.DrawString(e.Header.Text, headerFont,
                    Brushes.Black, e.Bounds, sf);
            }
        }
        return;
    }

    // Forces each row to repaint itself the first time the mouse moves over 
    // it, compensating for an extra DrawItem event sent by the wrapped 
    // Win32 control.
    private void listView1_MouseMove(object sender, MouseEventArgs e)
    {
        ListViewItem item = listView1.GetItemAt(e.X, e.Y);
        if (item != null && item.Tag == null)
        {
            listView1.Invalidate(item.Bounds);
            item.Tag = "tagged";
        }
    }

}

import System.*;
import System.Drawing.*;
import System.Drawing.Drawing2D.*;
import System.Globalization.*;
import System.Windows.Forms.*;

public class ListViewOwnerDraw extends Form
{
    private ListView myListView;
    private ContextMenu myContextMenu;

    public ListViewOwnerDraw()
    {
        // Create and initialize the ListView control.
        myListView = new ListView();
        myListView.set_BackColor(Color.get_Black());
        myListView.set_ForeColor(Color.get_White());
        myListView.set_Dock(DockStyle.Fill);
        myListView.set_View(View.Details);

        // Add columns to the ListView control.
        myListView.get_Columns().Add("Name", 72, HorizontalAlignment.Center);
        myListView.get_Columns().Add("First", 72, HorizontalAlignment.Center);
        myListView.get_Columns().Add("Second", 72, HorizontalAlignment.Center);
        myListView.get_Columns().Add("Third", 72, HorizontalAlignment.Center);

        // Create items and add them to the ListView control.
        ListViewItem listViewItem1 = new ListViewItem(new String[] 
            { "One", "20", "30", "-40" }, -1);
        ListViewItem listViewItem2 = new ListViewItem(new String[] 
            { "Two", "-250", "145", "37" }, -1);
        ListViewItem listViewItem3 = new ListViewItem(new String[] 
            { "Three", "200", "800", "-1,001" }, -1);
        ListViewItem listViewItem4 = new ListViewItem(new String[] 
            { "Four", "not available", "-2", "100" }, -1);
        myListView.get_Items().AddRange(new ListViewItem[] { listViewItem1, 
            listViewItem2, listViewItem3, listViewItem4 });

        // Create a shortcut menu for changing views and 
        // assign it to the ListView control.
        myContextMenu = new ContextMenu();
        myContextMenu.get_MenuItems().Add("List", 
            new EventHandler(menuItemList_Click));
        myContextMenu.get_MenuItems().Add("Details", 
            new EventHandler(menuItemDetails_Click));
        myListView.set_ContextMenu(myContextMenu);

        // Configure the ListView control for owner-draw and add 
        // handlers for the owner-draw events.
        myListView.set_OwnerDraw(true);
        myListView.add_DrawItem(new DrawListViewItemEventHandler(
            myListView_DrawItem));
        myListView.add_DrawSubItem(new DrawListViewSubItemEventHandler(
            myListView_DrawSubItem));

        // Add a handler for the MouseUp event so an item can be 
        // selected by clicking anywhere along its width.
        myListView.add_MouseUp(new MouseEventHandler(myListView_MouseUp));

        // Initialize the form and add the ListView control to it.
        this.set_ClientSize(new Size(292, 79));
        this.set_FormBorderStyle(get_FormBorderStyle().FixedSingle);
        this.set_MaximizeBox(false);
        this.set_Text("ListView OwnerDraw Example");
        this.get_Controls().Add(myListView);
    } //ListViewOwnerDraw

    // Clean up any resources being used.        
    protected void Dispose(boolean disposing)
    {
        if (disposing) {
            myContextMenu.Dispose();
        }
        super.Dispose(disposing);
    } //Dispose

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.Run(new ListViewOwnerDraw());
    } //main

    // Sets the ListView control to the List view.
    private void menuItemList_Click(Object sender, EventArgs e)
    {
        myListView.set_View(View.List);
    } //menuItemList_Click

    // Sets the ListView control to the Details view.
    private void menuItemDetails_Click(Object sender, EventArgs e)
    {
        myListView.set_View(View.Details);
    } //menuItemDetails_Click

    // Selects and focuses an item when it is clicked anywhere along 
    // its width. The click must normally be on the parent item text.
    private void myListView_MouseUp(Object sender, MouseEventArgs e)
    {
        ListViewItem clickedItem = myListView.GetItemAt(5, e.get_Y());
        if (clickedItem != null) {
            clickedItem.set_Selected(true);
            clickedItem.set_Focused(true);
        }
    } //myListView_MouseUp

    // Draws the backgrounds for the column header row and for entire
    // ListView items.
    private void myListView_DrawItem(Object sender, DrawListViewItemEventArgs e)
    {
        // Draw the background for the column header row.
        if (e.get_ItemIndex() == -1) {
            e.get_Item().set_BackColor(Color.get_Black());
            e.DrawBackground();
        }
        // Draw the background for a selected item.
        else {
            if (Convert.ToInt32((e.get_State() & ListViewItemStates.Selected))
                != 0) {
                e.get_Graphics().FillRectangle(Brushes.get_Maroon(),
                    e.get_Bounds());
                e.DrawFocusRectangle();
            }
            // Draw the background for an unselected item.
            else {
                LinearGradientBrush myBrush = new LinearGradientBrush(
                    e.get_Bounds(), Color.get_Orange(), Color.get_Maroon(),
                    LinearGradientMode.Horizontal);
                try {
                    e.get_Graphics().FillRectangle(myBrush, e.get_Bounds());
                }
                finally {
                    myBrush.Dispose();
                }    
            }
        }
        // Draw the item text for views other than the Details view.
        if (!(((ListView)sender).get_View().Equals(View.Details))) {
            e.DrawText();
        }
    } //myListView_DrawItem

    // Draws subitem text and applies content-based formatting.
    private void myListView_DrawSubItem(Object sender,
        DrawListViewSubItemEventArgs e)
    {
        TextFormatFlags flags = TextFormatFlags.Left;
        StringFormat sf = new StringFormat();
        try {
            // Store the column text alignment, letting it default
            // to Left if it has not been set to Center or Right.
            if (e.get_Header().get_TextAlign().
                Equals(HorizontalAlignment.Center)) {

                sf.set_Alignment(StringAlignment.Center);
                flags = TextFormatFlags.HorizontalCenter;
            }
            else {
                if (e.get_Header().get_TextAlign().
                    Equals(HorizontalAlignment.Right)) {

                    sf.set_Alignment(StringAlignment.Far);
                    flags = TextFormatFlags.Right;
                }
            }
            // Draw the text for a column header.
            if (e.get_ItemIndex() == -1) {
                Font myFont = new Font("Helvetica", 12, FontStyle.Bold);
                try {
                    e.get_Graphics().DrawString(e.get_Item().get_Text(), 
                        myFont, Brushes.get_White(), 
                        new PointF((float)e.get_Bounds().get_X(), 
                        (float)e.get_Bounds().get_Y()), sf);
                }
                finally {
                    myFont.Dispose();
                }
                return;
            }

            // Draw the text and background for a subitem with a 
            // negative value. 
            double subItemValue = 0;
            if (e.get_ColumnIndex() > 0 && System.Double.TryParse(
                e.get_Item().get_SubItems().get_Item(e.get_ColumnIndex()).
                get_Text(), NumberStyles.Currency, 
                NumberFormatInfo.get_CurrentInfo(), subItemValue) 
                && subItemValue < 0) {

                // Unless the item is selected, draw the standard 
                // background to make it stand out from the gradient.
                if (Convert.ToInt32(e.get_ItemState() 
                    & ListViewItemStates.Selected) == 0) {
                    e.DrawBackground();
                }
                // Draw the subitem text in red to highlight it. 
                e.get_Graphics().DrawString(e.get_Item().get_SubItems().
                    get_Item(e.get_ColumnIndex()).get_Text(), 
                    ((ListView)sender).get_Font(), Brushes.get_Red(), 
                    RectangleF.op_Implicit(e.get_Bounds()), sf);

                return;
            }
            // Draw normal text for a subitem with a nonnegative 
            // or nonnumerical value.
            e.DrawText(flags);
        }
        finally {
            sf.Dispose();
        }
    } //myListView_DrawSubItem
} //ListViewOwnerDraw 

System.Object
   System.EventArgs
    System.Windows.Forms.DrawListViewSubItemEventArgs

Les membres statiques publics (Shared en Visual Basic) de ce type sont thread-safe. Il n'est pas garanti que les membres d'instance soient thread-safe.

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

.NET Framework

Prise en charge dans : 2.0

Ajouts de la communauté

AJOUTER
Afficher:
© 2015 Microsoft