DrawListViewSubItemEventArgsとは? わかりやすく解説

DrawListViewSubItemEventArgs クラス

メモ : このクラスは、.NET Framework version 2.0 で新しく追加されたものです。

ListView.DrawSubItem イベントのデータを提供します。

名前空間: System.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

Public Class DrawListViewSubItemEventArgs
    Inherits EventArgs
Dim instance As DrawListViewSubItemEventArgs
public class DrawListViewSubItemEventArgs :
 EventArgs
public ref class DrawListViewSubItemEventArgs
 : public EventArgs
public class DrawListViewSubItemEventArgs extends
 EventArgs
public class DrawListViewSubItemEventArgs extends
 EventArgs
解説解説

ListView.DrawSubItem イベントを使用すると、詳細ビューにおける ListView コントロールの外観をカスタマイズ (またはオーナー描画) できます。

ListView コントロールの ListView.OwnerDraw プロパティが true に設定され、View プロパティが Details に設定されると、ListView.DrawSubItem イベントが発生します。イベント ハンドラに渡される DrawListViewSubItemEventArgs には、描画する ListViewItem.ListViewSubItem に関する情報が格納されます。さらに、サブ項目の描画に役立つメソッドも用意されています。

描画するサブ項目の親項目に関する情報を取得するには、ItemState プロパティまたは Item プロパティを使用します。ListViewItem.ListViewSubItem 自体を取得するには、SubItem プロパティを使用します。サブ項目が表示される列のヘッダーを表す ColumnHeader を取得するには、Header プロパティを使用します。

Graphics プロパティを使用して、Bounds プロパティで指定される領域内で実際に描画を行います。カスタマイズを必要としない標準の ListView 要素を描画するには、DrawBackground メソッド、DrawText メソッド、および DrawFocusRectangle メソッドを使用します。

サブ項目をオペレーティング システムによって描画する場合には、DrawDefault プロパティを使用します。これは特定のサブ項目だけをカスタマイズする場合に便利です。

メモメモ

オーナー描画の際にグラフィックがちらつく問題を回避するには、ListView コントロールをオーバーライドし、DoubleBuffered プロパティを true に設定します。この機能は、Windows XP および Windows Server 2003 ファミリでアプリケーションから Application.EnableVisualStyles メソッドを呼び出す場合にのみ使用できます。

使用例使用例

ListView コントロールのカスタム描画を提供する方法を示すコード例を次に示します。例の中の ListView コントロールには、グラデーションの背景が使用されています。負の値を持つサブ項目は、赤の前景色と黒の背景色で表されます。

ListView.DrawItem イベントのハンドラはすべての項目の背景を描画します。ListView.DrawSubItem イベントのハンドラは、テキスト値を描画し、負の値を持つサブ項目についてはテキストと背景の両方を描画します。DrawColumnHeader イベントのハンドラは、各列ヘッダーを描画します。

ContextMenu コンポーネントは、詳細ビューとリスト ビューの切り替えを行う手段を提供します。リスト ビューでは、ListView.DrawItem イベントのみが発生します。この場合、ListView.DrawItem イベント ハンドラでテキストと背景の両方が描画されます。

Imports System
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Globalization
Imports System.Windows.Forms

Public Class ListViewOwnerDraw
    Inherits Form
    Private WithEvents listView1 As
 New ListView()
    Private WithEvents contextMenu1 As
 New ContextMenu()
    Private WithEvents listMenuItem As
 New MenuItem("List")
    Private WithEvents detailsMenuItem As
 New MenuItem("Details")

    Public Sub New()

        ' Initialize the shortcut menu. 
        contextMenu1.MenuItems.AddRange(New MenuItem() _
            {Me.listMenuItem, Me.detailsMenuItem})

        ' Initialize the ListView control.
        With Me.listView1
            .BackColor = Color.Black
            .ForeColor = Color.White
            .Dock = DockStyle.Fill
            .View = View.Details
            .FullRowSelect = True
            .OwnerDraw = True
            .ContextMenu = Me.contextMenu1
        End With

        ' Add columns to the ListView control.
        With Me.listView1.Columns
            .Add("Name", 72, HorizontalAlignment.Center)
            .Add("First", 72, HorizontalAlignment.Center)
            .Add("Second", 72, HorizontalAlignment.Center)
            .Add("Third", 72, HorizontalAlignment.Center)
        End With

        ' Create items and add them to the ListView control.
        Dim listViewItem1 As New
 ListViewItem(New String() _
            {"One", "20",
 "30", "-40"}, -1)
        Dim listViewItem2 As New
 ListViewItem(New String() _
            {"Two", "-250",
 "145", "37"}, -1)
        Dim listViewItem3 As New
 ListViewItem(New String() _
            {"Three", "200",
 "800", "-1,001"},
 -1)
        Dim listViewItem4 As New
 ListViewItem(New String() _
            {"Four", "not available",
 "-2", "100"}, -1)
        Me.listView1.Items.AddRange(New ListViewItem()
 _
            {listViewItem1, listViewItem2, listViewItem3, listViewItem4})

        ' Initialize the form and add the ListView control to it.
        With Me
            .ClientSize = New Size(292, 79)
            .FormBorderStyle = FormBorderStyle.FixedSingle
            .MaximizeBox = False
            .Text = "ListView OwnerDraw Example"
            .Controls.Add(Me.listView1)
        End With

    End Sub

    ' Clean up any resources being used.        
    Protected Overrides Sub
 Dispose(ByVal disposing As Boolean)
        If disposing Then
            contextMenu1.Dispose()
        End If
        MyBase.Dispose(disposing)
    End Sub

    <STAThread()> _
    Shared Sub Main()
        Application.Run(New ListViewOwnerDraw())
    End Sub

    ' Sets the ListView control to the List view.
    Private Sub menuItemList_Click(ByVal
 sender As Object, _
        ByVal e As EventArgs) _
        Handles listMenuItem.Click

        Me.listView1.View = View.List

    End Sub

    ' Sets the ListView control to the Details view.
    Private Sub menuItemDetails_Click(ByVal
 sender As Object, _
        ByVal e As EventArgs) _
        Handles detailsMenuItem.Click

        Me.listView1.View = View.Details

        ' Reset the tag on each item to re-enable the workaround 
        ' in the MouseMove event handler.
        For Each item As
 ListViewItem In listView1.Items
            item.Tag = Nothing
        Next

    End Sub

    ' Selects and focuses an item when it is clicked anywhere along
 
    ' its width. The click must normally be on the parent item text.
    Private Sub listView1_MouseUp(ByVal
 sender As Object, _
        ByVal e As MouseEventArgs) _
        Handles listView1.MouseUp

        Dim clickedItem As ListViewItem = Me.listView1.GetItemAt(5,
 e.Y)
        If Not (clickedItem Is
 Nothing) Then
            clickedItem.Selected = True
            clickedItem.Focused = True
        End If

    End Sub

    ' Draws the backgrounds for entire ListView items.
    Private Sub listView1_DrawItem(ByVal
 sender As Object, _
        ByVal e As DrawListViewItemEventArgs)
 _
        Handles listView1.DrawItem

        If Not (e.State And
 ListViewItemStates.Selected) = 0 Then

            ' Draw the background for a selected item.
            e.Graphics.FillRectangle(Brushes.Maroon, e.Bounds)
            e.DrawFocusRectangle()

        Else

            ' Draw the background for an unselected item.
            Dim brush As New
 LinearGradientBrush(e.Bounds, Color.Orange, _
                Color.Maroon, LinearGradientMode.Horizontal)
            Try
                e.Graphics.FillRectangle(brush, e.Bounds)
            Finally
                brush.Dispose()
            End Try

        End If

        ' Draw the item text for views other than the Details view.
        If Not Me.listView1.View
 = View.Details Then
            e.DrawText()
        End If

    End Sub

    ' Draws subitem text and applies content-based formatting.
    Private Sub listView1_DrawSubItem(ByVal
 sender As Object, _
        ByVal e As DrawListViewSubItemEventArgs)
 _
        Handles listView1.DrawSubItem

        Dim flags As TextFormatFlags = TextFormatFlags.Left

        Dim sf As New StringFormat()
        Try

            ' Store the column text alignment, letting it default
            ' to Left if it has not been set to Center or Right.
            Select Case e.Header.TextAlign
                Case HorizontalAlignment.Center
                    sf.Alignment = StringAlignment.Center
                    flags = TextFormatFlags.HorizontalCenter
                Case HorizontalAlignment.Right
                    sf.Alignment = StringAlignment.Far
                    flags = TextFormatFlags.Right
            End Select

            ' Draw the text and background for a subitem with a 
            ' negative value. 
            Dim subItemValue As Double
            If e.ColumnIndex > 0 AndAlso
 _
                Double.TryParse(e.SubItem.Text, NumberStyles.Currency,
 _
                NumberFormatInfo.CurrentInfo, subItemValue) AndAlso
 _
                subItemValue < 0 Then

                ' Unless the item is selected, draw the standard 
                ' background to make it stand out from the gradient.
                If (e.ItemState And ListViewItemStates.Selected)
 = 0 Then
                    e.DrawBackground()
                End If

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

                Return

            End If

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

        Finally
            sf.Dispose()
        End Try

    End Sub

    ' Draws column headers.
    Private Sub listView1_DrawColumnHeader(ByVal
 sender As Object, _
        ByVal e As DrawListViewColumnHeaderEventArgs)
 _
        Handles listView1.DrawColumnHeader

        Dim sf As New StringFormat()
        Try

            ' Store the column text alignment, letting it default
            ' to Left if it has not been set to Center or Right.
            Select Case e.Header.TextAlign
                Case HorizontalAlignment.Center
                    sf.Alignment = StringAlignment.Center
                Case HorizontalAlignment.Right
                    sf.Alignment = StringAlignment.Far
            End Select

            ' Draw the standard header background.
            e.DrawBackground()

            ' Draw the header text.
            Dim headerFont As New
 Font("Helvetica", 10, FontStyle.Bold)
            Try
                e.Graphics.DrawString(e.Header.Text, headerFont, _
                    Brushes.Black, e.Bounds, sf)
            Finally
                headerFont.Dispose()
            End Try

        Finally
            sf.Dispose()
        End Try

    End Sub

    ' 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 Sub listView1_MouseMove(ByVal
 sender As Object, _
        ByVal e As MouseEventArgs) _
        Handles listView1.MouseMove

        Dim item As ListViewItem = listView1.GetItemAt(e.X,
 e.Y)
        If Not item Is Nothing
 AndAlso item.Tag Is Nothing
 Then
            listView1.Invalidate(item.Bounds)
            item.Tag = "tagged"
        End If

    End Sub

End Class
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";
        }
    }

}
#using <System.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Drawing::Drawing2D;
using namespace System::Globalization;
using namespace System::Windows::Forms;

public ref class ListViewOwnerDraw: public
 Form
{
private:
   ListView^ listView1;
   System::Windows::Forms::ContextMenu^ contextMenu1;

public:
   ListViewOwnerDraw()
   {
      listView1 = gcnew ListView;
      contextMenu1 = gcnew System::Windows::Forms::ContextMenu;

      // 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.
      array<String^>^temp0 = {"One","20","30"
,"-40"};
      ListViewItem^ listViewItem1 = gcnew ListViewItem( temp0,-1 );
      array<String^>^temp1 = {"Two","-250","145"
,"37"};
      ListViewItem^ listViewItem2 = gcnew ListViewItem( temp1,-1 );
      array<String^>^temp2 = {"Three","200","800"
,"-1,001"};
      ListViewItem^ listViewItem3 = gcnew ListViewItem( temp2,-1 );
      array<String^>^temp3 = {"Four","not available","-2"
,"100"};
      ListViewItem^ listViewItem4 = gcnew ListViewItem( temp3,-1 );
      array<ListViewItem^>^temp4 = {listViewItem1,listViewItem2,listViewItem3
,listViewItem4};
      listView1->Items->AddRange( temp4 );

      // Initialize the shortcut menu and 
      // assign it to the ListView control.
      contextMenu1->MenuItems->Add( "List", gcnew EventHandler( this,
 &ListViewOwnerDraw::menuItemList_Click ) );
      contextMenu1->MenuItems->Add( "Details", gcnew EventHandler(
 this, &ListViewOwnerDraw::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 += gcnew DrawListViewItemEventHandler( this,
 &ListViewOwnerDraw::listView1_DrawItem );
      listView1->DrawSubItem += gcnew DrawListViewSubItemEventHandler( this,
 &ListViewOwnerDraw::listView1_DrawSubItem );
      listView1->DrawColumnHeader += gcnew DrawListViewColumnHeaderEventHandler(
 this, &ListViewOwnerDraw::listView1_DrawColumnHeader );

      //listView1.MouseMove += gcnew MouseEventHandler(&ListViewOwnerDraw::listView1_MouseMove);
      // Add a handler for the MouseUp event so an item can be 
      // selected by clicking anywhere along its width.
      listView1->MouseUp += gcnew MouseEventHandler( this,
 &ListViewOwnerDraw::listView1_MouseUp );

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

   // Clean up any resources being used.        
public:
   ~ListViewOwnerDraw()
   {
      if ( contextMenu1 != nullptr )
      {
         delete contextMenu1;
      }
   }

private:

   // Sets the ListView control to the List view.
   void menuItemList_Click( Object^ /*sender*/, EventArgs^ /*e*/
 )
   {
      listView1->View = View::List;
   }

   // Sets the ListView control to the Details view.
   void menuItemDetails_Click( Object^ /*sender*/, EventArgs^
 /*e*/ )
   {
      listView1->View = View::Details;
   }

   // Selects and focuses an item when it is clicked anywhere along
 
   // its width. The click must normally be on the parent item text.
   void listView1_MouseUp( Object^ /*sender*/, MouseEventArgs^
 e )
   {
      ListViewItem^ clickedItem = listView1->GetItemAt( 5, e->Y );
      if ( clickedItem != nullptr )
      {
         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) !=
 (ListViewItemStates)0 )
      {
         // Draw the background for a selected item.
         e->Graphics->FillRectangle( Brushes::Maroon, e->Bounds );
         e->DrawFocusRectangle();
      }
      else
      {
         // Draw the background for an unselected item.
         LinearGradientBrush^ myBrush = gcnew LinearGradientBrush( e->Bounds,Color::Orange,Color::Maroon,LinearGradientMode::Horizontal
 );
         try
         {
            e->Graphics->FillRectangle( myBrush, e->Bounds );
         }
         finally
         {
            if ( myBrush )
               delete (IDisposable^)myBrush;
         }
      }

      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;
      StringFormat^ sf = gcnew StringFormat;
      try
      {
         // 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,
 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)
 == (ListViewItemStates)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 );
      }
      finally
      {
         if ( sf )
            delete (IDisposable^)sf;
      }
   }

   // Draws column headers.
private:
   void listView1_DrawColumnHeader( Object^ /*sender*/, DrawListViewColumnHeaderEventArgs^
 e )
   {
      StringFormat^ sf = gcnew StringFormat;
      try
      {
         // 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.
         System::Drawing::Font^ headerFont = gcnew System::Drawing::Font( "Helvetica",10,FontStyle::Bold
 );
         try
         {
            e->Graphics->DrawString( e->Header->Text, headerFont, Brushes::Black,
 e->Bounds, sf );
         }
         finally
         {
            if ( headerFont )
               delete (IDisposable^)headerFont;
         }
      }
      finally
      {
         if ( sf )
            delete (IDisposable^)sf;
      }

      return;
   }

   // Forces the row the mouse is on to repaint itself. 
   void listView1_MouseMove( Object^ /*sender*/, MouseEventArgs^
 e )
   {
      ListViewItem^ item = listView1->GetItemAt( e->X, e->Y );
      if ( item != nullptr )
      {
         listView1->Invalidate( item->Bounds );
      }
   }
};

[STAThread]
int main()
{
   Application::Run( gcnew ListViewOwnerDraw );
}
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
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバの場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
DrawListViewSubItemEventArgs メンバ
System.Windows.Forms 名前空間
ListView
ListView.DrawSubItem
ListView.OwnerDraw
ListView.View
ListViewItem.ListViewSubItem
View

DrawListViewSubItemEventArgs コンストラクタ

メモ : このコンストラクタは、.NET Framework version 2.0 で新しく追加されたものです。

DrawListViewSubItemEventArgs クラスの新しいインスタンスを初期化します。

名前空間: System.Windows.Forms
アセンブリ: System.Windows.Forms (system.windows.forms.dll 内)
構文構文

Public Sub New ( _
    graphics As Graphics, _
    bounds As Rectangle, _
    item As ListViewItem, _
    subItem As ListViewSubItem, _
    itemIndex As Integer, _
    columnIndex As Integer, _
    header As ColumnHeader, _
    itemState As ListViewItemStates _
)
Dim graphics As Graphics
Dim bounds As Rectangle
Dim item As ListViewItem
Dim subItem As ListViewSubItem
Dim itemIndex As Integer
Dim columnIndex As Integer
Dim header As ColumnHeader
Dim itemState As ListViewItemStates

Dim instance As New DrawListViewSubItemEventArgs(graphics,
 bounds, item, subItem, itemIndex, columnIndex, header, itemState)
public DrawListViewSubItemEventArgs (
    Graphics graphics,
    Rectangle bounds,
    ListViewItem item,
    ListViewSubItem subItem,
    int itemIndex,
    int columnIndex,
    ColumnHeader header,
    ListViewItemStates itemState
)
public:
DrawListViewSubItemEventArgs (
    Graphics^ graphics, 
    Rectangle bounds, 
    ListViewItem^ item, 
    ListViewSubItem^ subItem, 
    int itemIndex, 
    int columnIndex, 
    ColumnHeader^ header, 
    ListViewItemStates itemState
)
public DrawListViewSubItemEventArgs (
    Graphics graphics, 
    Rectangle bounds, 
    ListViewItem item, 
    ListViewSubItem subItem, 
    int itemIndex, 
    int columnIndex, 
    ColumnHeader header, 
    ListViewItemStates itemState
)
public function DrawListViewSubItemEventArgs
 (
    graphics : Graphics, 
    bounds : Rectangle, 
    item : ListViewItem, 
    subItem : ListViewSubItem, 
    itemIndex : int, 
    columnIndex : int, 
    header : ColumnHeader, 
    itemState : ListViewItemStates
)

パラメータ

graphics

描画が実行される Graphics 表面。

bounds

内部描画の対象となる Rectangle。

item

描画する ListViewItem.ListViewSubItem の親である ListViewItem。

subItem

描画する ListViewItem.ListViewSubItem。

itemIndex

ListView.Items コレクション内の親 ListViewItem のインデックス。

columnIndex

ListView.Columns コレクション内の ListViewItem.ListViewSubItem 列のインデックス。

header

ListViewItem.ListViewSubItem が表示される列の ColumnHeader。

itemState

描画する ListViewItem.ListViewSubItem の親である ListViewItem の現在の状態を示す ListViewItemStates 値のビットごとの組み合わせ。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
DrawListViewSubItemEventArgs クラス
DrawListViewSubItemEventArgs メンバ
System.Windows.Forms 名前空間

DrawListViewSubItemEventArgs プロパティ


パブリック プロパティパブリック プロパティ

  名前 説明
パブリック プロパティ Bounds 描画する ListViewItem.ListViewSubItem のサイズと位置を取得します。
パブリック プロパティ ColumnIndex ListViewItem.ListViewSubItem が表示される ListView 列のインデックスを取得します。
パブリック プロパティ DrawDefault オーナー描画ではなくオペレーティング システムによって ListViewItem.ListViewSubItem を描画するかどうかを示す値を取得または設定します。
パブリック プロパティ Graphics ListViewItem.ListViewSubItem の描画に使用する Graphics を取得します。
パブリック プロパティ Header ListViewItem.ListViewSubItem が表示される ListView 列のヘッダーを取得します。
パブリック プロパティ Item 描画する ListViewItem.ListViewSubItem の親である ListViewItem を取得します。
パブリック プロパティ ItemIndex 描画する ListViewItem.ListViewSubItem の親である ListViewItem のインデックスを取得します。
パブリック プロパティ ItemState 描画する ListViewItem.ListViewSubItem の親である ListViewItem の現在の状態を取得します。
パブリック プロパティ SubItem 描画する ListViewItem.ListViewSubItem を取得します。
参照参照

関連項目

DrawListViewSubItemEventArgs クラス
System.Windows.Forms 名前空間
ListView
ListView.DrawSubItem
ListView.OwnerDraw
ListView.View
ListViewItem.ListViewSubItem
View

DrawListViewSubItemEventArgs メソッド


パブリック メソッドパブリック メソッド

プロテクト メソッドプロテクト メソッド
参照参照

関連項目

DrawListViewSubItemEventArgs クラス
System.Windows.Forms 名前空間
ListView
ListView.DrawSubItem
ListView.OwnerDraw
ListView.View
ListViewItem.ListViewSubItem
View

DrawListViewSubItemEventArgs メンバ

ListView.DrawSubItem イベントのデータを提供します。

DrawListViewSubItemEventArgs データ型で公開されるメンバを以下の表に示します。


パブリック コンストラクタパブリック コンストラクタ
  名前 説明
パブリック メソッド DrawListViewSubItemEventArgs DrawListViewSubItemEventArgs クラスの新しいインスタンスを初期化します。
パブリック プロパティパブリック プロパティ
  名前 説明
パブリック プロパティ Bounds 描画する ListViewItem.ListViewSubItem のサイズと位置を取得します。
パブリック プロパティ ColumnIndex ListViewItem.ListViewSubItem が表示される ListView 列のインデックスを取得します。
パブリック プロパティ DrawDefault オーナー描画ではなくオペレーティング システムによって ListViewItem.ListViewSubItem を描画するかどうかを示す値を取得または設定します。
パブリック プロパティ Graphics ListViewItem.ListViewSubItem の描画に使用する Graphics を取得します。
パブリック プロパティ Header ListViewItem.ListViewSubItem が表示される ListView 列のヘッダーを取得します。
パブリック プロパティ Item 描画する ListViewItem.ListViewSubItem の親である ListViewItem を取得します。
パブリック プロパティ ItemIndex 描画する ListViewItem.ListViewSubItem の親である ListViewItem のインデックスを取得します。
パブリック プロパティ ItemState 描画する ListViewItem.ListViewSubItem の親である ListViewItem の現在の状態を取得します。
パブリック プロパティ SubItem 描画する ListViewItem.ListViewSubItem を取得します。
パブリック メソッドパブリック メソッド
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

DrawListViewSubItemEventArgs クラス
System.Windows.Forms 名前空間
ListView
ListView.DrawSubItem
ListView.OwnerDraw
ListView.View
ListViewItem.ListViewSubItem
View



英和和英テキスト翻訳

英語⇒日本語日本語⇒英語

辞書ショートカット

すべての辞書の索引

「DrawListViewSubItemEventArgs」の関連用語

DrawListViewSubItemEventArgsのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



DrawListViewSubItemEventArgsのページの著作権

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2026 Microsoft.All rights reserved.

©2026 GRAS Group, Inc.RSS