简体   繁体   中英

WPF Update Listbox Databinding

I'm new to WPF and am working on Databinding a Listbox from a xml file, everything loads correctly when the program starts, however I'm having trouble making the listbox update after I insert a new record. Everything that I've read is pointing to use a ObservableCollection which I am, but I can't figure out how to get the Listbox to refresh. I have tried calling a update to the ItemsSource but it still doesn't seem to work. Ideally I would like to just have a Refresh button that A user can click to update the listbox. Does anyone have any suggestions on a calling a update to the list box Thanks Michael

public class ContactList 
{
    string contactFile = @"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml";

    public ContactList()
    {
    }

    public ContactList(string contactFullName, string contactCellNumber,string contactBusinessNumber, string contactExtension, string contactEmail, string contactStatus,string contactAuralinkStatus, string contactAuralinkID)
    {
        this.ContactFullName = contactFullName;
        this.ContactCellNumber = contactCellNumber;
        this.ContactBusinessNumber = contactBusinessNumber;
        this.ContactExtension = contactExtension;
        this.ContactEmail = contactEmail;
        this.ContactStatus = contactStatus;
        this.ContactAuralinkStatus = contactAuralinkStatus;
        this.ContactAuralinkID = contactAuralinkID;
    }



    private string ContactFullName;

    public string PropContactFullName
    {
        get { return ContactFullName; }
        set { ContactFullName = value; }
    }

    private string ContactCellNumber;

    public string PropContactCellNumber
    {
        get { return ContactCellNumber; }
        set { ContactCellNumber = value; }
    }

    private string ContactBusinessNumber;

    public string PropContactBusinessNumber
    {
        get { return ContactBusinessNumber; }
        set { ContactBusinessNumber = value; }
    }

    private string ContactEmail;

    public string PropContactEmail
    {
        get { return ContactEmail; }
        set { ContactEmail = value; }
    }

    private string ContactStatus;

    public string PropContactStatus
    {
        get { return ContactStatus; }
        set { ContactStatus = value; }
    }

    private string ContactAuralinkStatus;

    public string PropContactAuralinkStatus
    {
        get { return ContactAuralinkStatus; }
        set { ContactAuralinkStatus = value; }
    }


    public string ContactAuralinkID;

    public string PropContactAuralinkID
    {
        get { return ContactAuralinkID; }
        set { ContactAuralinkID = value; }
    }


    private string ContactExtension;

    public string PropContactExtension
    {
        get { return ContactExtension; }
        set { ContactExtension = value; }
    }


}

public class Contacts : System.Collections.ObjectModel.ObservableCollection<ContactList>
{
    string contactFile = @"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml";

//Added this
    public event NotifyCollectionChangedEventHandler CollectionChanged;

    protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        if (CollectionChanged != null)
        {
            CollectionChanged(this, e);
        }
    }

    public Contacts(): base()
    {

        getContactFile();

        XDocument doc = XDocument.Load(contactFile);
        var contacts = from r in doc.Descendants("Contact")
                       select new
                       {
                           FullName = r.Element("FullName").Value,
                           CellNumber = r.Element("CellNumber").Value,
                           BusinessNumber = r.Element("BusinessNumber").Value,
                           Extension = r.Element("Extension").Value,
                           Email = r.Element("Email").Value,
                           AuralinkID = r.Element("AuralinkID").Value
                       };
        foreach (var r in contacts)
        {
            Add(new ContactList(r.FullName,r.CellNumber , r.BusinessNumber,r.Extension, r.Email, "", "",r.AuralinkID));
        }  
    }


    private void getContactFile()
    {
        if (!File.Exists(contactFile))
        {
            new XDocument(
                new XElement("Contacts"
                )
            )
            .Save(contactFile);
        }
    }
}


private void addContactICON_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (!doesContactExist())
        {
            try
            {

                XDocument doc = XDocument.Load(@"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml");
                XElement contact = new XElement("Contact");
                contact.Add(new XElement("ContactID", contactID.ToString()));
                contact.Add(new XElement("FullName", contactNameLBL.Content.ToString()));
                contact.Add(new XElement("CellNumber", c1.Content.ToString()));
                contact.Add(new XElement("BusinessNumber", businessPhoneIcon.ToolTip.ToString()));
                contact.Add(new XElement("Extension", c3.Content.ToString()));
                contact.Add(new XElement("Email", emailIcon.ToolTip.ToString()));
                contact.Add(new XElement("AuralinkID", videoIcon.ToolTip.ToString()));

                doc.Element("Contacts").Add(contact);
                doc.Save(@"U:\Peridot\Users\" + Program.getUser.ToString() + ".xml");
                MessageBox.Show(contactNameLBL.Content.ToString() + " has been added to your contacts.");


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        else
            MessageBox.Show("Contact Already Exists");
    }

XAML

<StackPanel>
    <StackPanel.Resources>
        <local:Contacts x:Key="contactListobj"></local:Contacts>
    </StackPanel.Resources>
    <ListBox x:Name="contactList" Width="305" Margin="5,3,0,0" VerticalAlignment="Top" HorizontalAlignment="Left" ItemsSource="{Binding Source={StaticResource contactListobj}}" Height="450" IsSynchronizedWithCurrentItem="True">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" >
                    <TextBlock Text="{Binding PropContactFullName}" ToolTip="{Binding PropContactFullName}" Height="35" Width="175" FontSize="12"/>
                    <TextBlock x:Name="contactEmailLBL" Text="{Binding PropContactEmail}" ToolTip="{Binding PropContactEmail}" Cursor="Hand" Width="30" Height="35" MouseLeftButtonUp="contactEmailLBL_MouseLeftButtonUp" Foreground="{x:Null}" FontSize="1">
                        <TextBlock.Background>
                            <ImageBrush Stretch="Uniform" ImageSource="Images/emailICON.png"/>
                        </TextBlock.Background>
                    </TextBlock>
                    <TextBlock x:Name="cellNumberLBL" Text="{Binding PropContactCellNumber}" ToolTip="{Binding PropContactCellNumber}" Cursor="Hand" MouseLeftButtonUp="cellNumberLBL_MouseLeftButtonUp" Width="30" Height="35" Foreground="{x:Null}" FontSize="1">
                        <TextBlock.Background>
                            <ImageBrush Stretch="Uniform" ImageSource="Images/mobilePhoneICON.png"/>
                        </TextBlock.Background>
                    </TextBlock>
                    <TextBlock x:Name="businessNumberLBL" Text="{Binding PropContactBusinessNumber}" ToolTip="{Binding PropContactBusinessNumber}" Cursor="Hand" Width="30" Height="35" MouseLeftButtonUp="businessNumberLBL_MouseLeftButtonUp" Foreground="{x:Null}" FontSize="1">
                        <TextBlock.Background>
                            <ImageBrush Stretch="Uniform" ImageSource="Images/BusinessPhoneICON.png"/>
                        </TextBlock.Background>
                    </TextBlock>
                    <TextBlock x:Name="auralinkLBL" Text="{Binding PropContactAuralinkID}" ToolTip="{Binding PropContactAuralinkID}" Cursor="Hand" Width="30" Height="35" Foreground="{x:Null}" FontSize="1" MouseLeftButtonUp="auralinkLBL_MouseLeftButtonUp">
                        <TextBlock.Background>
                            <ImageBrush Stretch="Uniform" ImageSource="Images/VideoICON.png"/>
                        </TextBlock.Background>
                    </TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</StackPanel>

From what I can tell based on the source code for ObservableCollection , the problem is most likely that the Add method you are using to add ContactList objects to your ObservableCollection is part of the Collection class that ObservableCollection inherits from. This does not fire the CollectionChanged event on the ObservableCollection so your binding is never notified that the collection has changed. Try calling the OnCollectionChanged protected method after you add each item to the collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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