WPF - Observable集合绑定错误

时间:2013-05-03 18:35:47

标签: c# wpf data-binding observablecollection

我想创建一个将ObservableCollection连接到ListBox的简单程序。我写道:

public ObservableCollection<int> Values { get; set; }

public MainWindow()
{
    InitializeComponent();
    Values = new ObservableCollection<int>();
    Values.Add(1);
    DataContext = this;
}

然后我创建了按钮并写道:

public Button1_Clicke(object sender, RoutedEventArgs e)
{
    Values.Add(2);
}

XMAL:

<ListBox x:Name="list" ItemsSource="{Binding Path=Values}"/>

当窗口打开时,我能看到'1'值。 但是当我点击按钮时,列表框会更新项目。有什么问题?

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

<ListBox x:Name="list" ItemsSource="{Binding Path=Values}"/>

修改 我做了一个简单的样本如下:

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <StackPanel>

        <ListBox x:Name="list" ItemsSource="{Binding Path=Values}"/>
        <Button Click="Button_Click" Content="Test"></Button>
    </StackPanel>

</Window>

代码隐藏(Window1.xaml.cs)

using System.Collections.ObjectModel;

/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
    public ObservableCollection<int> Values { get; set; }

    public Window1()
    {
        InitializeComponent();

        Values = new ObservableCollection<int>();
        Values.Add(1);
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Values.Add(2);
    }
}

它按预期工作。因此,根据您下面的评论,为什么不尝试删除所有转换器以确保它是否正确。