简体   繁体   English

绑定ComboBox ItemsSource在WPF中不起作用

[英]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. 这有点奇怪,因为我在那里发现的每个例子都说我正在以正确的方式做事但我无法让我的ComboBox绑定在WPF中工作。

I just created an empty WPF Application. 我刚创建了一个空的WPF应用程序。

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: 这是我的xaml:

<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. 我尝试过绑定myCollection,Binding Path = myCollection,我尝试过设置DataContext和不设置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之后设置datacontext

 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. Sajeetheran答案可行的,因为XAML对象的初始化着眼于当前状态,并结合还有什么在那个时候 ,但如果一个人改变的财产,以别的东西会失败。 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. 对于大多数WPF场景,人们希望使用INotifyPropertyChange机制来允许XAML绑定处理动态更改。 If one wants to truly use the power of bindings it goes hand in hand with INotifyPropertyChange . 如果一个人想要真正使用绑定的力量,它与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; 绑定不知道更改,因为myCollection的引用不会通知世界状态的变化; 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. 为了便于此类通知,用于保存属性的类需要遵守INotifyPropertyChanged ,并且属性myCollection需要发送通知事件。 ( 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 ). 请注意,在您的情况下,它是主窗口,在技术上可行,但在MVVM范例中,您希望从dat中分离视图,并使用ViewModel类来保存实际数据并提供此通知 )。

 public MainWindow : INotifyPropertyChanged

Then provide the event that will be subscribed to by the binding targets to the item on the DataContext : 然后提供将由绑定目标订阅到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 然后提供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. 分配数据上下文后,您必须使用InitializeComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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