-1

我想知道通用代码有什么问题。这里是:

namespace Morse_Mail{

public partial class MainWindow : Window
{

    public ObservableCollection<Message> Messages { get; set; }


    public MainWindow()
    {
        Messages = new ObservableCollection<Message>();

        InitializeComponent();
    }


    // some code here



}

public class Message : INotifyPropertyChanged
{
    private string subject;
    private string date;
    private string sender;
    private string id;

    public string Subject
    {
        get { return subject; }
        set { subject = value; OnPropertyChanged("Subject"); }
    }
    public string Date
    {
        get { return date; }
        set { date = value; OnPropertyChanged("Date"); }
    }
    public string Sender
    {
        get { return sender; }
        set { sender = value; OnPropertyChanged("Sender"); }
    }
    public string ID { get; set; }

    public Message(string _Subject, string _Date, string _Sender, string _ID) 
    {
        Subject = _Subject;
        Date = _Date;
        Sender = _Sender;
        ID = _ID;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}}

我想将列表视图内容绑定到 Messages ObserverableCollection。这是我的 xaml 代码:

<Window x:Class="Morse_Mail.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Height="864.5" Width="1203.5" ResizeMode="NoResize" Title="Morse Mail" WindowStartupLocation="CenterScreen">
<Grid Height="830" VerticalAlignment="Top">
    <ListView x:Name="ListView" HorizontalAlignment="Left" Height="704" Margin="47,39,0,0" VerticalAlignment="Top" Width="600" IsSynchronizedWithCurrentItem="True"
              ItemsSource="{Binding Messages}">
        <ListView.View >
            <GridView AllowsColumnReorder="true">
                <GridViewColumn Width="300" Header="Subject" 
                                DisplayMemberBinding="{Binding subject}"/>
                <GridViewColumn Width="150" Header="Date" 
                                DisplayMemberBinding="{Binding date}"/>
                <GridViewColumn Width="120" Header="Sender" 
                                DisplayMemberBinding="{Binding sender}"/>
                <GridViewColumn Width="20" Header="ID" 
                                DisplayMemberBinding="{Binding id}"/>
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

我的应用程序有效,但如果我使用按钮将新项目添加到消息集合中,它们会出现在该集合中,但窗口中没有任何变化。为什么我的数据绑定不起作用以及如何

4

1 回答 1

3

您似乎没有设置DataContext. (它需要是持有你绑定到的属性的对象,这里是窗口)

于 2012-06-07T18:47:14.980 回答