WPF Show data from multiple DataContexts in ToolTip of ItemsControl

后端 未结 5 1968
清酒与你
清酒与你 2021-01-18 03:54

I am trying to display a tooltip for an item generated by an ItemsControl that needs to pull data from conceptually unrelated sources. For example, say I have a

5条回答
  •  野的像风
    2021-01-18 04:33

    After an hour of hair pulling I have come to the conviction that you can't reference another DataContext inside a DataTemplate for a ToolTip. For other Bindings it is perfectly possible as other posters have proven. That's why you can't use the RelativeSource trick either. What you can do is implement a static property on your Item class and reference that:

    
        
            
                
                    
                         
                            
                                
                                    
                                        
                                            
                                            
                                        
                                        
                                        
                                    
                                
                            
                        
                    
                
            
        
    
    
    using System.Collections.Generic;
    using System.Windows;
    
    namespace ToolTipSpike
    {
        public partial class Window1 : Window
        {
    
            public List Items { get; private set; }
            public Window1()
            {
                InitializeComponent();
                var itemList = new List
                      {
                          new Item { ItemName = "First Item", ItemDescription = "This is the first item." },
                          new Item { ItemName = "Second Item", ItemDescription = "This is the second item." }
                      };
                this.Items = itemList;
                this.DataContext = this;
           }
        }
    
         public class Item
         {
             static Item()
             {
                 GlobalText = "Additional Text";
             }
             public static string GlobalText { get; set; }
             public string ItemName{ get; set;}
             public string ItemDescription{ get; set;}
         }
    }
    

提交回复
热议问题