如何使用INotifyPropertyChanged更新ListBox

时间:2011-11-09 13:34:14

标签: c# wpf visual-studio inotifypropertychanged

我有一个日历,我在日历itemscontrol中嵌套了一个itemscontrol,这样我就可以在gridcell(日期)中显示我想要为其制作事件的事件。压延机有7列6行。现在我只是使用列表框来实际显示事件(标题)。我可以在启动时添加项目,但我希望能够在程序运行后添加/删除/更改。我曾经尝试过一次INotifyPropertyChanged,但我无法理解我的生活。如果有人可以拿走我所拥有的并向我展示或给我提示我如何做到这一点,我将非常感激。

我可以在启动前添加(项目)的类:

public class eventProperties : ObservableCollection<eventsTitles>
{
    //public string Eventer { get; set; }

    public eventProperties() : base() 
    {
        Add(new eventsTitles("First Test"));
        Add(new eventsTitles("First Test#2"));

    }

当我想在程序启动并运行时添加事件时,会弹出这个窗口(类)。我需要弄清楚如何使用此窗口添加项目以及如何将其添加到特定日期(gridcell)

    public Event(MainWindow parentform)
    {

        InitializeComponent();
        _parentForm = parentform;
        //this.month = month;
        //this.day = day;
        //this.year = year;
        lblCreateEvent.Content = "Create Event For " + month + " / " + day + " / " + year;

    }

    private void btnSubmit_Click(object sender, RoutedEventArgs e)
    {
        month = Convert.ToInt32(txtMonth.Text);
        day = Convert.ToInt32(txtDay.Text);
        year = Convert.ToInt32(txtYear.Text);



        Schedule sched = new Schedule();
        DateTime curr = DateTime.Now;
        int[] m = new int[7];
        DateTime newcurr = new DateTime(year, month, day);

        var cal = System.Globalization.DateTimeFormatInfo.CurrentInfo.Calendar;
        var ms = cal.GetWeekOfYear(new DateTime(newcurr.Year, newcurr.Month, 1), System.Globalization.CalendarWeekRule.FirstDay, System.DayOfWeek.Sunday);

           // for (var i = 1; newcurr.Month == 11; newcurr = newcurr.AddDays(1))
           // {

                var month_week = (newcurr.Day / 7);
                sched.MonthWeek = newcurr.GetWeekOfMonth().ToString();
                sched.Month = newcurr.Month.ToString();
                sched.Year = newcurr.Year.ToString();
                sched.day = newcurr.Day.ToString();
                sched.WeekOfYear = cal.GetWeekOfYear(newcurr, System.Globalization.CalendarWeekRule.FirstDay, DayOfWeek.Sunday).ToString();
                sched.dayofweek = newcurr.DayOfWeek.ToString();


                //Here is where the calender is created. By looping through all the days in the selected month it will find the weeknumber and day of the week -->
                // that that particular date belongs to and place in the correct gridcell.
                _parentForm.bindings.schedule.Add(new Schedule { WeekNo = newcurr.GetWeekOfMonth() - 1, WeekDay = (int)newcurr.DayOfWeek, day = newcurr.Day.ToString(), eventTitle = "Camper Calender"    });

这是我需要绑定所有内容的实际日历XAML。

     </customgridcontrol:GridControl>


     </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <Button Content="{Binding day}" Width="175" HorizontalAlignment="Stretch" VerticalAlignment="Top" VerticalContentAlignment="Top" HorizontalContentAlignment="Left" Name="btnCalenderDate" Click="btnCalenderDate_Click" Loaded="btnCalenderDate_Loaded" Height="18" FontSize="10" FontWeight="Bold">
                        </Button>

                        <ItemsControl  Height="60" VerticalAlignment="Stretch">
                            <ItemsControl.Resources>
                                <src:eventProperties x:Key="dataList"/>
                            </ItemsControl.Resources>
                            <ItemsControl.Items>
                                <ListBox ItemsSource="{Binding Source= {StaticResource dataList} }" DisplayMemberPath="EventTitle" VerticalAlignment="Top" IsSynchronizedWithCurrentItem="True">            
                                </ListBox>
                            </ItemsControl.Items>
                        </ItemsControl>
                    </StackPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
     <!-- ItemContainerStyle -->
        <ItemsControl.ItemContainerStyle>

            <Style >        
                    <Setter Property="Grid.Column" Value="{Binding WeekDay}"  />
                <Setter Property="Grid.Row" Value="{Binding WeekNo}" />
            </Style>
            </ItemsControl.ItemContainerStyle>
    </ItemsControl>

eventTitles类

  namespace Camp_
  {
       public class eventsTitles
       {
            public string eventTitle {get; set;} 

            public eventsTitles()//String ev)
            {
               // this.eventTitle = ev;
            }

            public string EventTitle
            {
                get { return eventTitle; }
                set { eventTitle = value; }
            }
       }        
  }

2 个答案:

答案 0 :(得分:2)

Harsh's answer对于您实现INotifyPropertyChanged的方式是正确的,但是您只需要为单个属性实现该方法。如果您要通知UI收集已更改,请使用ObservableCollection

因此,如果您的标签包含Event.EventTitle,并且您想要更改代码隐藏中的EventTitle,则应在INotifyPropertyChanged上实施EventClass,以便当您更新myEvent.EventTitle时,UI中的标签会自动更新为新值。

如果您在向集合中添加项目或从集合中删除项目时要自动更新ListBox(或ItemsControl),只需将ListBox绑定到ObservableCollection属性即可自动更新在添加或删除项目时更新UI。

例如,

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <StackPanel>
         <Button Content="{Binding day}" Click="AddEvent" />

         <ItemsControl Height="60" ItemsSource="{Binding Events}">
             <ItemsControl.ItemTemplate>
                 <DataTemplate>
                    <TextBlock Text="{Binding EventTitle}" />
                 <DataTemplate>
             </ItemsControl.ItemTemplate>
         </ItemsControl>
        </StackPanel>
    </DataTemplate>
</ItemsControl.ItemTemplate>

在此示例中,您的Schedule类将拥有一个名为Events的属性ObservableCollection<Event>。要添加新事件,您可以使用以下内容:

void AddEvent(object sender, EventArgs e)
{
    // Get the DataContext for the Button, which should be of type Schedule
    Schedule day = (sender as Button).DataContext as Schedule;

    // Add New Event. Since this is an ObservableCollection, UI will automatically update
    day.Events.Add(new Event { EventTitle = "Test Event" });
}

作为旁注,您应该查看一些.Net naming conventions

答案 1 :(得分:1)

我认为eventTitles必须遇到一些未实现INotifyPropertyChanged接口的问题,所以这里是实施的详细信息。

假设有eventTitles类

public class eventTitles : INotifyPropertyChanged
{
    private string _eventtitle = string.Empty;

    public string EventTitle
    {
       get {return _eventtitle;}

        set
        {
            if (value != _eventtitle)
            {
                _eventtitle = value;
                NotifyPropertyChanged("EventTitle");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

如需进一步参考,您可以查看此MSDN Post