绑定 ComboBox ItemsSource 在 WPF 中不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32166772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Binding ComboBox ItemsSource does not work in WPF
提问by RobertPorter
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. Nothing seems to be working.
我试过绑定 myCollection,绑定路径=myCollection,我试过设置和不设置 DataContext。似乎没有任何工作。
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.
我已经没有想法了,我在那里找到的每个例子都说这是正确的方法,它应该可以工作,所以感谢我提出的任何帮助。
采纳答案by Sajeetharan
Set the datacontext after InitializeComponent
之后设置数据上下文 InitializeComponent
InitializeComponent();
myCollection = new List<string> { "test1", "test2", "test3", "test4" };
DataContext = this;
回答by Dimitris Batsougiannis
at the end of your constructor
在构造函数的末尾
comboBox1.ItemsSource = myCollection;
回答by ΩmegaMan
Sajeetheran answer works because the initialize of the XAML objects looks at the current state and binds to what is there at that timebut will fail if one changes the property to something else. I would term that a one-timework-around.
Sajeetheran答案的作品,因为XAML的初始化对象在当前状态下的外观并结合还有什么在那个时候,但如果一个人改变的财产,以别的东西会失败。我将其称为一次性解决方法。
I just wanted to make this using bindings
我只是想用绑定来做这个
For most WPF scenarios one wants to use the INotifyPropertyChangemechanision to allow for dynamicchanges to be handled by the XAML bindings. If one wants to truly use the power of bindingsit goes hand in hand with INotifyPropertyChange. Otherwise Dimitri's answer is just as valid as Sajeetharan's.
对于大多数 WPF 方案,人们希望使用该INotifyPropertyChange机制来允许XAML 绑定处理动态更改。如果一个人想真正使用绑定的力量,它与INotifyPropertyChange. 否则,Dimitri 的回答与 Sajeetharan 的回答一样有效。
The binding does not know of the change because the reference of myCollectiondoes not notify the world of a change in status; hence the data doesn't get displayed.
绑定不知道更改,因为 的引用myCollection不会通知世界状态更改;因此数据不会显示。
To facilitate such notification the class used to hold the property needs to adhere to INotifyPropertyChangedand the property myCollectionneeds 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 ViewModelclass is used to hold the actual data and provide this notificaiton).
为了促进此类通知,用于持有属性的类需要遵守,INotifyPropertyChanged并且属性myCollection需要发送通知事件。(请注意,在您的情况下,它的主窗口在技术上是可行的,但在 MVVM 范式中,人们希望将视图与数据分开,并使用一个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.
然后提供change事件的机制。
/// <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"); }
}
回答by AZ_
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 InitializeComponentafter assigning data context.
您必须InitializeComponent在分配数据上下文之后。

