c# - 如何使用 INotifyPropertyChanged 更新列表框

标签 c# wpf visual-studio inotifypropertychanged

我有一个日历,并且在日历项目控件中嵌套了一个项目控件,以便我可以在我想要为其创建事件的网格单元(日期)中显示事件。压延机为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,我需要在其中绑定(bind)所有内容。

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

最佳答案

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

因此,如果您有一个包含 Event.EventTitle 的标签,并且您想要更改 EventTitle在代码隐藏中,您将实现 INotifyPropertyChanged关于EventClass这样当您更新myEvent.EventTitle时UI 中的标签将自动更新为新值。

如果您有一个 ListBox(或 ItemsControl),希望在向集合添加项目或从集合中删除项目时自动更新,只需绑定(bind) ListBoxObservableCollection属性,当添加或删除项目时,它将自动更新 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

关于c# - 如何使用 INotifyPropertyChanged 更新列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8065771/

相关文章:

C# 根据字符串同步线程

c# - 忽略更新时的某些列

c# - 使用 MVVM 构建选项列表

c# - 如何将 DesignInstance 与 Caliburn.Micro 一起使用

visual-studio - 如何在没有 Visual Studio 设计器的情况下查看 XAML 控件的默认模板和样式?

c# - 在 C# 中将单个属性包装在 #region 中是否有充分的理由?

c# - Raycast 和 Instantiate 的区别

wpf - Silverlight/WPF 和 Blend : DataBind a text field, 但定义设计时值?

visual-studio - 如何让 Resharper 正确包装很长的行?

c# - 每次运行时 Visual Studio 都会构建项目