简体   繁体   中英

Binding ComboBox ItemsSource does not work in WPF

This is kinda strange cause every example I found there says I'm doing things the right way yet I was unable to get my ComboBox binding to work in WPF.

I just created an empty WPF Application.

public List<string> myCollection { get; set; }

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
        myCollection = new List<string> {"test1", "test2", "test3", "test4"};
    }

And here is my xaml for this:

<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <ComboBox ItemsSource="{Binding Path=myCollection}" Height="23" HorizontalAlignment="Left" Margin="66,56,0,0" Name="comboBox1" VerticalAlignment="Top" Width="319" />
</Grid>

I have tried Binding myCollection, Binding Path=myCollection, I have tried with and without setting DataContext. Nothing seems to be working.

I have run out of ideas and every example I find out there says this is the correct way and it should be working so thanks for any help i advance.

Set the datacontext after InitializeComponent

 InitializeComponent();          
 myCollection = new List<string> { "test1", "test2", "test3", "test4" };
 DataContext = this;

在构造函数的末尾

comboBox1.ItemsSource = myCollection;

Sajeetheran answer works because the initialize of the XAML objects looks at the current state and binds to what is there at that time but will fail if one changes the property to something else. I would term that a one-time work-around .

I just wanted to make this using bindings

For most WPF scenarios one wants to use the INotifyPropertyChange mechanision to allow for dynamic changes to be handled by the XAML bindings. If one wants to truly use the power of bindings it goes hand in hand with INotifyPropertyChange . Otherwise Dimitri's answer is just as valid as Sajeetharan's.


The binding does not know of the change because the reference of myCollection does not notify the world of a change in status; hence the data doesn't get displayed.

To facilitate such notification the class used to hold the property needs to adhere to INotifyPropertyChanged and the property myCollection needs to send a notify event. ( Note in your case its the main window which is technically workable, but in the MVVM paradigm one wants to seperate the view from the dat and a ViewModel class is used to hold the actual data and provide this notificaiton ).

 public MainWindow : INotifyPropertyChanged

Then provide the event that will be subscribed to by the binding targets to the item on the DataContext :

 public event PropertyChangedEventHandler PropertyChanged;

Then the mechanism to provide the change event.

/// <summary>
/// Raises the PropertyChanged event.
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Then provide the change for the myCollection

private List<string> _myCollection;

public List<string> myCollection
{
    get { return _myCollection; }
    set { _myCollection= value; OnPropertyChanged("myCollection"); }
}
public List<string> myCollection { get; set; }

    public MainWindow()
    {            
        myCollection = new List<string> {"test1", "test2", "test3", "test4"};
        DataContext = this;

        InitializeComponent(); //-- call it at the end
    }

You have to InitializeComponent after assigning data context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM