Binding data to ComboBox WPF

前端 未结 3 1137
情歌与酒
情歌与酒 2021-01-25 13:51

I am newbie to WPF, and needs help to bind data into the ComboBox. The xaml file contains the tag below.



        
相关标签:
3条回答
  • 2021-01-25 13:58

    Instead of DataContext={Binding} you should have ItemsSource={Binding}.

    The data context for any frameworkelement in the visual tree is by default {Binding}.

     <ComboBox Name="_currentInbox"
          SelectedItem="Hoved"
          Width="180"
          Margin="5"
          Height="22"
          DisplayMemberPath="Name"
          ItemSource="{Binding}" /> 
    

    Also for the combobox to display text of the items correctly I suppose you need DisplayMemberPath too. I assumed the property from Inbox class that you need to display is Name. Please replace with your relevant property name.

    0 讨论(0)
  • 2021-01-25 14:03

    If your Inbox class is like,

    public class Inbox
    {
        public int ID { get; set; }
        public string Text { get; set; }
    }
    

    And if you do not want to change your xmal, the code behind method should be like this,

    public void FillInboxes(List<Inbox> inboxes) 
        {
            _currentInbox.DisplayMemberPath = "Text"; // To display the 'Text' property in the combobox dropdown
            //_currentInbox.DisplayMemberPath = "ID"; // To display the 'ID' property in the combobox dropdown
            _currentInbox.DataContext = inboxes; 
        }
    
    0 讨论(0)
  • 2021-01-25 14:21

    I assume your Inbox class consists of two properties (for simplicity), but there may be any number of them:

    public class Inbox
    {
        public int ID { get; set; }
        public string Text { get; set; }
    }
    

    You write a DataTemplate, for example:

    <Grid.Resources>
        <DataTemplate x:Key="InboxTemplate">
            <WrapPanel>
                <TextBlock Text="{Binding Path=ID}"/>
                <TextBlock>:</TextBlock>
                <TextBlock Text="{Binding Path=Text}"/>
            </WrapPanel>
        </DataTemplate>
    </Grid.Resources>
    

    Then correct your ComboBox declaration like:

    <ComboBox Name="_currentInbox" Width="180"  Margin="5" Height="22" ItemsSource="{Binding}" ItemTemplate="{StaticResource InboxTemplate}" />
    

    Finally you set DataContext of your ComboBox to your List<Inbox>:

    public void FillInboxes(List<Inbox> inboxes)
    {
       _currentInbox.DataContext = inboxes;
    }
    

    EDIT: As you've asked for a simpler solution, you can just override ToString() method of your Inbox class:

    protected override string ToString()
    {
        return ID.ToString() + ":" + Text;
    }
    
    0 讨论(0)
提交回复
热议问题