2009-03-25 15 views

cevap

0

Kendi UserControl hesabınızı oluşturmanız gerekir.

Bir açılan kutudaki her öğe için bir ToolTip'e sahip olmak sıra dışı bir gereksinimdir; belki 2 sütun birleşik giriş kutusu kullanabilirdiniz?

+0

Nasıl do iki sütunlu bir combo yapmak? –

+0

Etrafında birkaç ücretsiz olanlar var. Bunu kod projesinde buldum ama kullanmadım ve ne kadar iyi olduğuna dair yorum yapamam: http://www.codeproject.com/KB/cpp/multicolumncombo.aspx –

+7

Bunun sıra dışı olduğunu düşünmüyorum hiç Ortak durum, öğenin metninin çok uzun olması ve dizenin kuyruğunu göremiyor olmanızdır. Bir araç ipucu, öğeyi görüntülemenin çok açık bir yoludur. İki sütunlu bir combo, rahatsız ve korkunç geliyor. – Andrew

6
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e) 
{ 
    ToolTip toolTip1 = new ToolTip(); 
    toolTip1.AutoPopDelay = 0; 
    toolTip1.InitialDelay = 0; 
    toolTip1.ReshowDelay = 0; 
    toolTip1.ShowAlways = true; 
    toolTip1.SetToolTip(this.comboBox1, comboBox1.Items[comboBox1.SelectedIndex].ToString()) ; 
} 
+3

Bu işe yarayacak olsa da, aynı zamanda araç ipucu arasında güçlü bir bağlantı yaratacaktır (artık bir değişkene atamaksızın oluşturmuş olmanızın hiçbir yolu yoktur). Yani comboBox'a kaldırmaya çalışırsanız. Her ne kadar görünürden uzaklaşacaktır. Hafızada kalacak. Sadece bu değil, indeksi her değiştirdiğinizde yeni araç ipuçlarıyla bağ kuruyorsunuz. Araç ipucunu daha yüksek bir kapsama alıp şu şekilde çağırırdım: özel void comboBox1_SelectedIndexChanged (nesne gönderen, System.EventArgs e) { myGolbalToolTip.SetToolTip (this.comboBox1, yourString); –

+0

Bu şekilde, kapsamın içinde veya dışında, tüm bağlantıları kaldırmak için myGlobalToolTip.RemoveAll() öğesini arayabilir ve sonra denetimi bellekten kaldırabilirsiniz. Ama bu sadece dinamik olarak nesneler oluşturuyorsanız. –

26

Aslında bu soruna birkaç makul çözüm var. Bir MSDN forumu iki olasılık, nobugz ve bir tane de agrobler içeren bir ComboBox Item highlight event mesajına sahiptir. Bunların her biri, ComboBox açılır menüsündeki her bir öğenin araç ipuçlarını ele alması gereken bir ComboBox alt sınıfına kod sağlar. Agrobler'in çözümü, bazı güzel çizimler içerdiği için, daha cilalı görünüyor, ancak maalesef kontrolün önemli ToolTipMember özelliğini nasıl dolduracağımız net değil (en azından benim için).

Her iki çözüm de, tek tek öğelere atanan isteğe bağlı araç ipuçlarına izin veriyor gibi görünüyor. Daha spesifik, ancak daha yaygın olan bir durum, ComboBox'un genişliğini sığmayacak kadar uzun olan öğelerin olabileceğini bildiğinizde, araç ipucunun öğenin metnini yansıtmasını istediğiniz yerdir. Kendi durumumda, tam dosya yollarını tutan bir ComboBox örneğim var, bu nedenle içeriğin ComboBox'ın genişliğini aşabileceğini görmek kolay.

Zhi-Xin Ye, MSDN forumu Windows Dropdown question'da, bu daha özel sorunu gideren ve çok daha basit bir çözüm sağlar. Kodu bütünüyle burada yeniden yapıyorum. (Bu kodun Form1 adında bir Form oluşturulan ve işleyici gösterilen yükü bağladım ve ayrıca comboBox1 adlı ComboBox ve bir araç ipucu işleyicisi toolTip1 eklemiş önceden varsayar unutmayın.)

private void Form1_Load(object sender, EventArgs e) 
{ 
    this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed; 
    this.comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem); 
} 

void comboBox1_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    string text = this.comboBox1.GetItemText(comboBox1.Items[e.Index]); 
    e.DrawBackground(); 
    using (SolidBrush br = new SolidBrush(e.ForeColor)) 
    { e.Graphics.DrawString(text, e.Font, br, e.Bounds); } 

    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
    { this.toolTip1.Show(text, comboBox1, e.Bounds.Right, e.Bounds.Bottom); } 
    else { this.toolTip1.Hide(comboBox1); } 
    e.DrawFocusRectangle(); 
} 

basit ve özlü, bu kodun iken bir kusurdan muzdarip (yukarıdaki MSDN iş parçacığına bir yanıtta belirtildiği gibi): fareyi bir tıklatma öğesinden diğerine (tıklamadan) hareket ettirdiğinizde, yalnızca her diğer biri kalıcı bir ipucu gösterir! düzeltme, yalnızca bu iş parçacığı üzerinde bir başka girişle ima, yüzden tam sağlanması yararlı olacaktır düşünülmektedir, kodu buraya düzeltilmiş:

private void Form1_Load(object sender, EventArgs e) 
{ 
    comboBox1.DrawMode = DrawMode.OwnerDrawFixed; 
    comboBox1.DrawItem += comboBox1_DrawItem; 
    comboBox1.DropDownClosed += comboBox1_DropDownClosed; 
} 

private void comboBox1_DropDownClosed(object sender, EventArgs e) 
{ 
    toolTip1.Hide(comboBox1); 
} 

private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    if (e.Index < 0) { return; } // added this line thanks to Andrew's comment 
    string text = comboBox1.GetItemText(comboBox1.Items[e.Index]); 
    e.DrawBackground(); 
    using (SolidBrush br = new SolidBrush(e.ForeColor)) 
    { e.Graphics.DrawString(text, e.Font, br, e.Bounds); } 
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
    { toolTip1.Show(text, comboBox1, e.Bounds.Right, e.Bounds.Bottom); } 
    e.DrawFocusRectangle(); 
} 

birkaç kod gereksiz kısımlarını çıkararak yanında (örneğin, "bu "niteleyici" birincil fark, toolTip1.Hide çağrısı DropDownClosed olay işleyicisine taşınmaktır. DrawItem işleyiciden çıkartmak yukarıda belirtilen kusuru ortadan kaldırır; ancak açılır kapanır kapanmaz, aksi takdirde son görüntülenen araç ipucu ekranda kalır.

2012.07.31 Zeyilname Sadece Kitaplığımı kullanırsanız size hiç yazmak için hiçbir kod var bu nedenle bu ipucu kapasitesini içeren bir kompozit ComboBox oluşturulan beri var olduğunu hatırlatmak istedik. Sadece bir ComboBoxWithTooltip'i Visual Studio tasarımcısına sürükleyin ve işiniz bitti. Başlamak için API page veya download açık kaynak kodlu C# kitaplığımdaki ComboBoxWithTooltip'e aşağıya inin. (Yakalanan Andrew hatası için yama, yakında çıkacak 1.1.04 sürümünde olacak.)

+3

Sadece bir uyarı ... Eğer "DropDownStyle", "DropDownList" olarak ayarlanmışsa, bu gerçekten işe yaramaz. Eğer 'DropDownList' kullanırsanız, 'e.Index'in -1'den büyük olduğundan emin olmanız gerekir. – Andrew

+0

@Andrew'ı yakaladığınız için teşekkürler! Ortaya çıkan çalışma zamanı hatasını önlemek için yukarıdaki kodu değiştirdim. –

+0

Bunu (Visual Studio 2013 - .NET 2.0 Project - Windows 8 çalıştı.1) ve metin sınırları, sonuna kadar boş bir alan bırakarak sağa doğru gidiyor gibi görünmüyor. Ayrıca, "DropDownList" DropDownStyle ile, liste açılır pencereden daha uzunsa, araç ipucu hayalet öğeyi izler. –

0

Veri kaynağından yüklüyorsanız, verileri veri tabanına alın ve aynı kutucuğa ayarlayın. Verilerim üç sütun ID, NAME, DEFINITION var.

InputQuery = "select * from ds_static_frequency"; 
     TempTable = UseFunc.GetData(InputQuery); 

     cmbxUpdateFrequency.DataSource = TempTable; 
     cmbxUpdateFrequency.DataTextField = "NAME"; 
     cmbxUpdateFrequency.DataValueField = "ID"; 
     cmbxUpdateFrequency.DataBind(); 

     foreach (DataRow dr in TempTable.Rows) 
     {     
      int CurrentRow = Convert.ToInt32(dr["ID"].ToString()); 
      cmbxUpdateFrequency.Items[CurrentRow - 1].ToolTip = dr["Definition"].ToString();    
     }  
+0

Yanlış! Winform combobox öğesinde "ToolTip" özelliği yok. – woohoo

+0

Evet, woohoo haklı. – Balaji

2

Çözümümün: Aşağıda benim kodudur Michael Sorens gelen solüsyon üzerine

ToolTip toolTip = new ToolTip() { AutoPopDelay = 0, InitialDelay = 0, ReshowDelay = 0, ShowAlways = true, }; 
comboBox.DrawMode = DrawMode.OwnerDrawFixed; 
comboBox.DrawItem += (s, e) => 
{ 
    e.DrawBackground(); 
    string text = comboBox.GetItemText(comboBox.Items[e.Index]); 
    using (SolidBrush br = new SolidBrush(e.ForeColor)) 
     e.Graphics.DrawString(text, e.Font, br, e.Bounds); 
    if ((e.State & DrawItemState.Selected) == DrawItemState.Selected && comboBox.DroppedDown) 
     toolTip.Show(text, comboBox, e.Bounds.Right, e.Bounds.Bottom + 4); 
    e.DrawFocusRectangle(); 
}; 
comboBox.DropDownClosed += (s, e) => 
    toolTip.Hide(comboBox); 
1

Bina (birkaç hata ve eklenen özellikler sabit). Bir kaç şey yapar:

  • Bu bir XML dosyasından bu durumda (kitap başlığını açılan ile ilişkili bir dosyanın önizlemesini görüntüler veya ipucu daha açıklamalar ekleyebilir veya ekran yapabilirsiniz tamamen farklı bir şey.
  • Açılır menüde "0" konumu için ipucu görüntülenmiyor (bir yer tutucum vardı, ancak ikinci if bildiriminde e.index>0'u kaldırabilirsiniz).
  • Açılan tuş KAPALI olduğunda araç ipucunu göstermez.

    private void comboBox1_DrawItem(object sender, DrawItemEventArgs e) 
    { 
        ComboBox comboBox1 = (ComboBox)sender; 
        if (e.Index >= 0) 
        {//Draws all items in drop down menu 
         String text = comboBox1.GetItemText(comboBox1.Items[e.Index]); 
         e.DrawBackground(); 
         using (SolidBrush br = new SolidBrush(e.ForeColor)) 
         { 
          e.Graphics.DrawString(text, e.Font, br, e.Bounds); 
         } 
    
         if ((e.State & DrawItemState.Selected) == DrawItemState.Selected && e.Index > 0 && comboBox1.DroppedDown) 
         {//Only draws tooltip when item 1+ are highlighted. I had a "--" placeholder in the 0 position 
          try 
          { 
           XmlDocument doc; 
           XmlNode testNode; 
           doc = new XmlDocument(); 
           String testXMLDoc = String.Format(@"{0}\{1}.xml", filePath, fileName);//global variables 
           String toolTip = "---Preview of File---"; 
           doc.Load(testXMLDoc); 
           testNode = doc.SelectSingleNode("/Books"); 
           if (testNode.HasChildNodes) 
           { 
            XmlNodeList nodeList = testNode.SelectNodes("Book"); 
            foreach (XmlNode xmlNode in nodeList) 
            { 
             toolTip += "\r\n" + xmlNode.SelectSingleNode("Title").InnerXml; 
            } 
           } 
           this.toolTipHelp.Show(toolTip, comboBox1, e.Bounds.Right, e.Bounds.Bottom); 
          } 
          catch (Exception tp) 
          { 
           Debug.WriteLine("Error in comboBox1 tooltip: " + tp); 
          } 
         } 
         else 
         { 
          this.toolTipHelp.Hide(comboBox1); 
         } 
        } 
        else 
        { 
         this.toolTipHelp.Hide(comboBox1); 
        } 
        e.DrawFocusRectangle(); 
    } 
    
0

Çözümümün:

public class ToolTipComboBox: ComboBox 
{ 
    #region Fields 

    private ToolTip toolTip; 
    private bool _tooltipVisible; 
    private bool _dropDownOpen; 
    #endregion 

    #region Types 

    [StructLayout(LayoutKind.Sequential)] 
    // ReSharper disable once InconsistentNaming 
    public struct COMBOBOXINFO 
    { 
     public Int32 cbSize; 
     public RECT rcItem; 
     public RECT rcButton; 
     public ComboBoxButtonState buttonState; 
     public IntPtr hwndCombo; 
     public IntPtr hwndEdit; 
     public IntPtr hwndList; 
    } 

    public enum ComboBoxButtonState 
    { 
     // ReSharper disable once UnusedMember.Global 
     StateSystemNone = 0, 
     // ReSharper disable once UnusedMember.Global 
     StateSystemInvisible = 0x00008000, 
     // ReSharper disable once UnusedMember.Global 
     StateSystemPressed = 0x00000008 
    } 

    [DllImport("user32.dll")] 
    public static extern bool GetComboBoxInfo(IntPtr hWnd, ref COMBOBOXINFO pcbi); 
    [DllImport("user32.dll", SetLastError = true)] 
    public static extern bool GetWindowRect(IntPtr hwnd, out RECT lpRect); 

    #endregion 

    #region Properties 

    private IntPtr HwndCombo 
    { 
     get 
     { 
      COMBOBOXINFO pcbi = new COMBOBOXINFO(); 
      pcbi.cbSize = Marshal.SizeOf(pcbi); 
      GetComboBoxInfo(Handle, ref pcbi); 
      return pcbi.hwndCombo; 
     } 
    } 

    private IntPtr HwndDropDown 
    { 
     get 
     { 
      COMBOBOXINFO pcbi = new COMBOBOXINFO(); 
      pcbi.cbSize = Marshal.SizeOf(pcbi); 
      GetComboBoxInfo(Handle, ref pcbi); 
      return pcbi.hwndList; 
     } 
    } 

    [Browsable(false)] 
    public new DrawMode DrawMode 
    { 
     get { return base.DrawMode; } 
     set { base.DrawMode = value; } 
    } 

    #endregion 

    #region ctor 

    public ToolTipComboBox() 
    { 
     toolTip = new ToolTip 
     { 
      UseAnimation = false, 
      UseFading = false 
     }; 

     base.DrawMode = DrawMode.OwnerDrawFixed; 
     DrawItem += OnDrawItem; 
     DropDownClosed += OnDropDownClosed; 
     DropDown += OnDropDown; 
     MouseLeave += OnMouseLeave; 
    } 

    #endregion 

    #region Methods 

    private void OnDropDown(object sender, EventArgs e) 
    { 
     _dropDownOpen = true; 
    } 

    private void OnMouseLeave(object sender, EventArgs e) 
    { 
     ResetToolTip(); 
    } 

    private void ShowToolTip(string text, int x, int y) 
    { 
     toolTip.Show(text, this, x, y); 
     _tooltipVisible = true; 
    } 

    private void OnDrawItem(object sender, DrawItemEventArgs e) 
    { 
     ComboBox cbo = sender as ComboBox; 
     if (e.Index == -1) return; 

     // ReSharper disable once PossibleNullReferenceException 
     string text = cbo.GetItemText(cbo.Items[e.Index]); 
     e.DrawBackground(); 

     if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) 
     { 
      TextRenderer.DrawText(e.Graphics, text, e.Font, e.Bounds.Location, SystemColors.Window); 

      if (_dropDownOpen) 
      { 
       Size szText = TextRenderer.MeasureText(text, cbo.Font); 
       if (szText.Width > cbo.Width - SystemInformation.VerticalScrollBarWidth && !_tooltipVisible) 
       { 
        RECT rcDropDown; 
        GetWindowRect(HwndDropDown, out rcDropDown); 

        RECT rcCombo; 
        GetWindowRect(HwndCombo, out rcCombo); 

        if (rcCombo.Top > rcDropDown.Top) 
        { 
         ShowToolTip(text, e.Bounds.X, e.Bounds.Y - rcDropDown.Rect.Height - cbo.ItemHeight - 5); 
        } 
        else 
        { 
         ShowToolTip(text, e.Bounds.X, e.Bounds.Y + cbo.ItemHeight - cbo.ItemHeight); 
        } 
       } 
      } 
     } 
     else 
     { 
      ResetToolTip(); 
      TextRenderer.DrawText(e.Graphics, text, e.Font, e.Bounds.Location, cbo.ForeColor); 
     } 

     e.DrawFocusRectangle(); 
    } 

    private void OnDropDownClosed(object sender, EventArgs e) 
    { 
     _dropDownOpen = false; 
     ResetToolTip(); 
    } 

    private void ResetToolTip() 
    { 
     if (_tooltipVisible) 
     { 
      // ReSharper disable once AssignNullToNotNullAttribute 
      toolTip.SetToolTip(this, null); 
      _tooltipVisible = false; 
     } 
    } 

    #endregion 
} 
0

Aşağıda genişliği açılan kutu denetimi genişliğinden daha büyüktür açılan kutunun öğe üzerinde araç ipucu göstermek için C# kodudur. Araç ipucu böyle açılan kutu üzerindeki kullanıcı vurgulu bir kez gösterilir: Burada

this.combo_box1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; 
this.combo_box1.DrawMode = DrawMode.OwnerDrawFixed; 
this.combo_box1.DrawItem += new DrawItemEventHandler(combo_box1_DrawItem); 
this.combo_box1.DropDownClosed += new EventHandler(combo_box1_DropDownClosed); 
this.combo_box1.MouseLeave += new EventHandler(combo_box1_Leave); 

void combo_box1_DrawItem(object sender, DrawItemEventArgs e) 
     { 
      if (e.Index < 0) { return; } 
      string text = combo_box1.GetItemText(combo_box1.Items[e.Index]); 
      e.DrawBackground(); 
      using (SolidBrush br = new SolidBrush(e.ForeColor)) 
      { 
       e.Graphics.DrawString(text, e.Font, br, e.Bounds); 
      } 

      if ((e.State & DrawItemState.Selected) == DrawItemState.Selected && combo_box1.DroppedDown) 
      { 
       if (TextRenderer.MeasureText(text, combo_box1.Font).Width > combo_box1.Width) 
       { 
        toolTip1.Show(text, combo_box1, e.Bounds.Right, e.Bounds.Bottom); 
       } 
       else 
       { 
        toolTip1.Hide(combo_box1); 
       } 
      } 
      e.DrawFocusRectangle(); 
     } 

     private void combo_box1_DropDownClosed(object sender, EventArgs e) 
     { 
      toolTip1.Hide(combo_box1); 
     } 

     private void combo_box1_Leave(object sender, EventArgs e) 
     { 
      toolTip1.Hide(combo_box1); 
     } 

     private void combo_box1_MouseHover(object sender, EventArgs e) 
     { 
      if (!combo_box1.DroppedDown && TextRenderer.MeasureText(combo_box1.SelectedItem.ToString(), combo_box1.Font).Width > combo_box1.Width) 
      { 
       toolTip1.Show(combo_box1.SelectedItem.ToString(), combo_box1, combo_box1.Location.X, combo_box1.Location.Y); 
      } 
     } 

fazla ayrıntı için link - WPF ile http://newapputil.blogspot.in/2016/12/display-tooltip-for-combo-box-item-cnet.html

0

kullandığınız bir ComboBox.ItemTemplate

<ComboBox    
    ItemsSource="{Binding Path=ComboBoxItemViewModels}" 
    SelectedValue="{Binding SelectedComboBoxItem, 
    SelectedValuePath="Name"     
> 
    <ComboBox.ItemTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding Path=Name}" ToolTip="{Binding Path=Description}"/> 
    </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox>