WPF Show data from multiple DataContexts in ToolTip of ItemsControl

后端 未结 5 1966
清酒与你
清酒与你 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

    I had a very similar problem and arrived at this question seeking answers. In the end I came up with a different solution that worked in my case and may be useful to others.

    In my solution, I added a property to the child item that references the parent model, and populated it when the children were generated. In the XAML for the ToolTip, I then simply referenced the property from the parent model on each element and set the DataContext to the parent model property.

    I felt more comfortable with this solution than creating proxy elements in XAML and referencing them.

    Using the example code for this question, you would do the following. Note I have not tested this scenario in a compiler, but have done so successfully implemented this solution in the code for my own scenario.

    Item:

    public class Item
    {
        public List Parent { get; set; }
        public string ItemDescription { get; set; }
        public string ItemName { get; set; }
    }
    

    Window:

    public partial class Window1 : Window
        {
            public Window1()
            {
                InitializeComponent();
    
                List itemList = new List();
                itemList.Add(new Item() { Parent = this, ItemName = "First Item", ItemDescription = "This is the first item." });
                itemList.Add(new Item() { Parent = this, ItemName = "Second Item", ItemDescription = "This is the second item." });
    
    
                this.Items = itemList;
                this.GlobalText = "Something else for the tooltip.";
                this.DataContext = this;
            }
    
            public string GlobalText { get; private set; }
    
            public List Items { get; private set; }
        }
    

    XAML:

    
        
            
                
                    
                        
                            
                                
                                    
                                    
                                
                                
                                
                            
                        
                    
                
            
        
    
    

提交回复
热议问题