WPF: How to bind object to ComboBox

后端 未结 3 1391
清歌不尽
清歌不尽 2020-12-13 02:13

Trying to learn how to bind objects to various types of controls. In this instance, I want to get sample data in my object to appear in ComboBox. The code runs but what appe

3条回答
  •  孤街浪徒
    2020-12-13 02:54

    There are several ways to tell the framework what to display

    1) Use DisplayMemberPath on the ComboBox (this will display the named property):

    
    

    2) Set ItemTemplate on the ComboBox. This is like #1, except allows you to define a template to display, rather than just a property:

    
        
            
                
                    
                
            
        
    
    

    3) Add a ToString() override to source class. Useful if you always want to display the same string for a given class. (Note that the default ToString() is just the class type name, which is why you see "TheProtect.UserControls.Client".)

    public class Client
    {
        // ...
    
        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, ID);
        }
    }
    

    4) Add a DataTemplate to the XAML resources. This is useful for associating a given class type with a more complex or stylized template.

    
        
            
                
            
        
    
        // ...
    
        
    

提交回复
热议问题