绑定 ComboBox ItemsSource 在 WPF 中不起作用

Binding ComboBox ItemsSource does not work in WPF

这有点奇怪,因为我在那里找到的每个示例都说我正在以正确的方式做事,但我无法让我的 ComboBox 绑定在 WPF 中工作。

我刚刚创建了一个空的 WPF 应用程序。

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

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

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

我试过绑定 myCollection、绑定路径=myCollection,我试过设置和不设置 DataContext。 似乎没有任何效果。

我 运行 没有想法,我在那里找到的每个例子都说这是正确的方法,它应该有效,所以感谢我提出的任何帮助。

InitializeComponent

之后设置数据上下文
 InitializeComponent();          
 myCollection = new List<string> { "test1", "test2", "test3", "test4" };
 DataContext = this;

在构造函数的末尾

comboBox1.ItemsSource = myCollection;

Sajeetheran 的回答有效,因为 XAML 对象的初始化会查看当前状态并绑定到 当时 的状态,但如果更改属性 到别的地方。我认为 一次性 解决方法.

I just wanted to make this using bindings

对于大多数 WPF 方案,人们希望使用 INotifyPropertyChange 机制来允许 动态 更改由 XAML 绑定处理。如果一个人想真正使用 bindings 的力量,它与 INotifyPropertyChange 齐头并进。否则 Dimitri 的回答与 Sajeetharan 的一样有效。


绑定不知道更改,因为 myCollection 的引用不会通知世界状态的更改;因此数据不会显示。

为了便于通知,用于保存 属性 的 class 需要遵守 INotifyPropertyChanged 并且 属性 myCollection 需要发送通知事件。 (请注意,在您的情况下,它的主要 window 在技术上是可行的,但在 MVVM 范例中,人们希望将视图与数据分开,而 ViewModel class 是用于保存实际数据并提供此通知)。

 public MainWindow : INotifyPropertyChanged

然后将绑定目标订阅的事件提供给 DataContext 上的项目:

 public event PropertyChangedEventHandler PropertyChanged;

然后提供变化事件的机制。

/// <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));
    }
}

然后为 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
    }

分配数据上下文后,您必须InitializeComponent