WPF Databinding combobox to a list

前端 未结 3 1245
温柔的废话
温柔的废话 2021-02-19 08:18

I am having a difficult time trying to bind my property which is of type List to my combobox through XAML.

public List MyProperty  { get; set; }


        
相关标签:
3条回答
  • 2021-02-19 08:36

    If you don't specify anything than just the path, the binding assumes as a source the container DataContext. By the way, the useful property is defined on the container (e.g. the window).

    You may solve it as follows (in the xaml):

    ItemsSource="{Binding Path=MyProperty, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}}"
    
    0 讨论(0)
  • 2021-02-19 08:38

    Posting my comment back to mark the answer.

    My DataContext was set, BUT it was set after InitializeComponent(). I thought that could be the problem. Then I realized that as I am binding through xaml, when the view loads, the binding happens to the property which is empty.

    The property gets populated when the view is ready after its loaded (i.e on _presenter.OnViewReady()). Since it's not an observable collection nothing gets added to the combobox. Specifying it from my code behind works, because at that time the data exists in the property.

    0 讨论(0)
  • 2021-02-19 08:45

    Assume you have a List<Foo> called Foos in your window / page. Foo has a property Name. Now you set up the binding in XAML as follows:

    <ComboBox ItemsSource="{Binding Path=Foos}"
    DisplayMemberPath="Name"
    SelectedValuePath="Name"
    SelectedValue="{Binding Path=Foo}"
    />
    

    This is based on this SO question. Read this (WPF DataBinding overview) as a good foundation for databinding in WPF.

    0 讨论(0)
提交回复
热议问题