2013-08-12 39 views
1

在我的wpf應用程序中,我有兩個位於DataTemplate中的timePicker控件。在DataTemplate中設置TimePicker的日期和時間

的XAML:

<Controls:MetroWindow 
    x:Class="TimeSheet.DayView" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:e="http://schemas.microsoft.com/developer/msbuild/2003" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:l="clr-namespace:TimeSheet.Views.DataTemplateSpace" 
    xmlns:sys="clr-namespace:System;assembly=mscorlib" 
    xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro" 
    xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit" 
    x:Name="MainWin" 
    Title="DayView" Width="596" Height="596"> 

<Window.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colours.xaml" /> 
      <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Fonts.xaml" /> 
      <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" /> 
      <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/Blue.xaml" /> 
      <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Accents/BaseLight.xaml" /> 
     </ResourceDictionary.MergedDictionaries> 

     <!-- <Style x:Key="ColoringStyle" TargetType="{x:Type ListBoxItem}"> 
      <EventSetter Event="MouseDoubleClick" Handler="ListBoxItem_MouseDoubleClick"/> 
      <Style.Triggers> 
       <DataTrigger Binding="{Binding isSynced}" Value="true"> 
        <Setter Property="Background" Value="Gold"></Setter> 
       </DataTrigger> 
       <DataTrigger Binding="{Binding isSynced}" Value="false"> 
        <Setter Property="Background" Value="Aqua"></Setter> 
       </DataTrigger> 
      </Style.Triggers> 
     </Style>--> 

     <!-- Default DataTemplate --> 
     <DataTemplate x:Key="DefaultDataTemplate" > 
      <StackPanel Orientation="Horizontal" Width="596"> 
       <TextBlock Text="{Binding ClientNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="145"/> 
       <TextBlock Text="{Binding ApplicationNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="90"/> 
       <TextBlock Text="{Binding StartTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="100"/> 
       <TextBlock Text="{Binding StopTimeBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="60"/> 
       <TextBlock Text="{Binding TaskNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="71"/> 
       <TextBlock Text="{Binding ProjectNameBinding}" Background="Transparent" Padding="0" Margin="0" TextWrapping="Wrap" Width="130"/> 
      </StackPanel> 
     </DataTemplate> 

     <!-- Editable DataTemplate --> 
     <DataTemplate x:Key="EditableDataTemplate"> 
      <StackPanel Orientation="Horizontal" Width="596"> 
       <!--<ComboBox x:Name="ClientComboBox" SelectionChanged="ClientComboBoxChanged" ItemsSource="{Binding Path=clientList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ClientNameBindingClass, Mode=OneWayToSource}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="145"/>--> 
       <TextBox Name="CltText" Text="{Binding ClientNameBinding,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="145"/> 
       <TextBox Name="AppText" Text="{Binding ApplicationNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="90"/> 
       <xctk:TimePicker Name="StartPicker" Value="{Binding StartValue, ElementName=MainWin, Mode=TwoWay}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/> 
       <xctk:TimePicker Name="EndPicker" Value="{Binding EndValue, ElementName=MainWin, Mode=TwoWay}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="60" EndTime="11:59:0"/> 
       <TextBox Name="TaskText" Text="{Binding TaskNameBinding}" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" TextWrapping="Wrap" Width="71"/> 
       <ComboBox x:Name="ProjectComboBox" ItemsSource="{Binding Path=projectList, ElementName=MainWin}" SelectedValuePath="_id" DisplayMemberPath="_name" SelectedItem="{Binding ProjectNameBindingClass, Mode=OneWayToSource}" Width="130" Background="Yellow" BorderThickness="0"/> 
      </StackPanel> 
     </DataTemplate> 


     <!-- DataTemplate Selector --> 

     <l:DayViewListDataTemplateSelector x:Key="templateSelector" 
      DefaultDataTemplate="{StaticResource DefaultDataTemplate}" 
      EditableDataTemplate="{StaticResource EditableDataTemplate}"/> 

    </ResourceDictionary> 

</Window.Resources> 


    <Viewbox Stretch="Fill" Width="{Binding Width, ElementName=MainWin}" Height="{Binding Height, ElementName=MainWin}"> 
    <Grid Margin="0,0,0,-4" Background="#FF3399FF" Height="557"> 

     <Button x:Name="BackButton" Style="{DynamicResource MetroCircleButtonStyle}" Content="&lt;---" Foreground="Blue" Click="BackButton_Click" Margin="7,2,524,491"/> 
     <Button x:Name="TimerButton" Width="124" Height="46" Click="TimerButton_Click" Margin="172,12,300,499"> 
      <Button.Background> 
       <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> 
        <GradientStop Color="Black" Offset="0"/> 
        <GradientStop Color="White" Offset="1"/> 
        <GradientStop Color="#FF5B6CB8"/> 
       </LinearGradientBrush> 
      </Button.Background> 
     </Button> 
     <Label x:Name="monthLabel" Content="May" RenderTransformOrigin="2.34,0.545" FontFamily="Times New Roman" FontSize="20" Margin="431,2,90,522"/> 
     <Label x:Name="dayDateLabel" Content="Friday, 27" RenderTransformOrigin="0.446,0.226" FontFamily="Times New Roman" FontSize="36" FontWeight="Bold" Margin="376,35,38,467"/> 
     <StackPanel Orientation="Horizontal" Margin="-1,93,1,434" RenderTransformOrigin="1.155,0.47" Height="25"> 
      <TextBox Text="Client" HorizontalContentAlignment="Center" Width="145" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/> 
      <TextBox Text="Application" HorizontalContentAlignment="Center" Width="90" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/> 
      <TextBox Text="StartTime" HorizontalContentAlignment="Center" Canvas.Left="148" Canvas.Top="86" Width="100" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" RenderTransformOrigin="0.5,0.5" VerticalContentAlignment="Center"/> 
      <TextBox Text="StopTime" HorizontalContentAlignment="Center" Width="60" RenderTransformOrigin="0.471,0.692" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/> 
      <TextBox Text="Task" HorizontalContentAlignment="Center" Canvas.Left="378" Canvas.Top="86" Width="130" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/> 
      <TextBox Text="Project" HorizontalContentAlignment="Center" Width="71" Foreground="White" Background="Blue" Padding="0" BorderThickness="0" VerticalContentAlignment="Center"/> 
     </StackPanel> 

     <ListBox x:Name="listBox1" ItemsSource="{Binding}" Margin="0,131,0,59" ItemTemplateSelector="{StaticResource templateSelector}" SelectionMode="Single"> 
      <ListBox.ItemContainerStyle> 
       <Style TargetType="{x:Type ListBoxItem}"> 
        <EventSetter Event="MouseDoubleClick" Handler="listBox1_MouseDoubleClick"> 
        </EventSetter> 
       </Style> 
      </ListBox.ItemContainerStyle> 
     </ListBox> 

     <Button x:Name="SyncEntry" Content="Sync All" HorizontalAlignment="Left" Margin="476,498,0,0" VerticalAlignment="Top" Width="95" Click="SyncEntry_Click"> 
      <Button.Background> 
       <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> 
        <GradientStop Color="Black" Offset="0"/> 
        <GradientStop Color="White" Offset="1"/> 
        <GradientStop Color="#FF5256AC"/> 
       </LinearGradientBrush> 
      </Button.Background> 
     </Button> 
     <Button x:Name="EditButton" Content="Edit" HorizontalAlignment="Left" Margin="393,498,0,0" VerticalAlignment="Top" Width="75" Click="EditButton_Click"> 
      <Button.Background> 
       <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> 
        <GradientStop Color="Black" Offset="0"/> 
        <GradientStop Color="White" Offset="1"/> 
        <GradientStop Color="#FF5256AC"/> 
       </LinearGradientBrush> 
      </Button.Background> 
     </Button> 
     <Button x:Name="CustomButton" Content="Add" HorizontalAlignment="Left" Margin="0,70,0,0" VerticalAlignment="Top" Width="75" FontSize="12" Height="20" FontWeight="Normal" Click="CustomButton_Click"/> 
    </Grid> 
</Viewbox> 

</Controls:MetroWindow> 

C#:

public partial class DayView : MetroWindow, INotifyPropertyChanged 
{ 
    private DateTime currentDateForWindow; 

    public List<Harvest_Project> projectList{get;set;} 

    public List<Harvest_Client> clientList {get; set;} 

    public Harvest_Project selectedProjectid {get; set;} 

    public Harvest_Client selectedClientid {get; set;} 

    public string ElementName { get; set; } 

    private DateTime _dateTime1; 
    public DateTime StartValue 
    { 
     get 
     { 
      return _dateTime1; 
     } 
     set 
     { 
      _dateTime1 = value; 
      OnPropertyChanged("StartValue"); 
     } 
    } 

    private DateTime _dateTime2; 
    public DateTime EndValue 
    { 
     get 
     { 
      return _dateTime2; 
     } 
     set 
     { 
      _dateTime2 = value; 
      OnPropertyChanged("EndValue"); 
     } 
    } 

    public DayView(DateTime s) 
    { 
      InitializeComponent(); 
      this.DataContext = this; 

      Globals._globalController.setDayViewWindow(this); 

      currentDateForWindow = s; 

      dayDateLabel.Content = s.DayOfWeek + ", " + s.Day; 
      monthLabel.Content = s.ToString("MMMM"); 

      if(Globals._globalController.win32Manager.isTimerRunning) 
       TimerButton.Content = "Stop"; 
      else 
       TimerButton.Content = "Start"; 

      listBox1.Items.Clear(); 

      listBox1.MouseDoubleClick += new MouseButtonEventHandler(listBox1_MouseDoubleClick); 
      clientList = Globals._globalController.harvestManager._CLIENTLIST; 
      projectList = Globals._globalController.harvestManager._PROJECTLIST; 
      Globals._globalController.fetchAndPopulateForDate(currentDateForWindow); 

      Globals.ni2 = new NotifyIcon(); 
      Globals.ni2.Icon = TimeSheet.Properties.Resources.DayViewIcon; 
      Globals.ni2.Visible = true; 
      Globals.ni2.Click += 
      delegate(object sender, EventArgs args) 
      { 
       this.Show(); 
       this.WindowState = WindowState.Normal; 

      }; 

    } 

    protected override void OnStateChanged(EventArgs e) 
    { 
     if (WindowState == System.Windows.WindowState.Minimized) 
     { 
      this.Hide(); 
      Globals.ni2.BalloonTipTitle = "DayView"; 
      Globals.ni2.BalloonTipText = "This is Day window"; 
      Globals.ni2.Visible = true; 
      Globals.ni2.ShowBalloonTip(500); 
      base.OnStateChanged(e); 
     } 
    } 

    public void addHarvestEntrytoView(Harvest_TimeSheetEntry entry) 
    { 

      listBox1.Items.Add(entry); 

    } 

    public void addHarvestEntrytoView(List<Harvest_TimeSheetEntry> entry) 
    { 
     foreach (Harvest_TimeSheetEntry x in entry) 
      listBox1.Items.Add(x); 
    } 

    private void BackButton_Click(object sender, RoutedEventArgs e) 
    { 
      Globals.ni2.Visible=false; 
      this.Hide(); 
      Globals._globalController.getMonthViewWindow.Show(); 
      Globals.ni1.Visible = true; 
    } 

    private void TimerButton_Click(object sender, RoutedEventArgs e) 
    { 
     if (!Globals._globalController.win32Manager.isTimerRunning) 
     { 
      Globals._globalController.win32Manager.startTimer(); 
      this.TimerButton.Content = "Stop"; 
     } 
     else 
     { 
      Globals._globalController.win32Manager.stopTimer(); 
      this.TimerButton.Content = "Start"; 
     } 
    } 


    private void SyncEntry_Click(object sender, RoutedEventArgs e) 
    { 
     //Submit All unsynced Entries 

     foreach(Harvest_TimeSheetEntry item in listBox1.Items) 
     { 
      if (!item.isSynced) 
      { 
       if (item.ProjectNameBinding == "Select Project" && item.ClientNameBinding == "Select Client") 
        System.Windows.MessageBox.Show("Please select you Project and Client"); 
       else 
       //Check if something is selected in selectedProjectItem For that item 
       Globals._globalController.harvestManager.postHarvestEntry(item); 
       System.Windows.MessageBox.Show("Entry posted"); 
      } 
     } 

    } 



    private void listBox1_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
    { 
     //Submit clicked Entry 
     if (sender is ListBoxItem) 
     { 
      ListBoxItem item = (ListBoxItem)sender; 
      Harvest_TimeSheetEntry entryToPost = (Harvest_TimeSheetEntry)item.DataContext; 

      if (!entryToPost.isSynced) 
      { 
       //Check if something is selected in selectedClientItem and selectedProjectItem For that items 
       if (entryToPost.ClientNameBinding == "Select Client" || entryToPost.ProjectNameBinding == "Select Project") 
        System.Windows.MessageBox.Show("Please select you Project and Client"); 
       else 
       { 
        Globals._globalController.harvestManager.postHarvestEntry(entryToPost); 
        System.Windows.MessageBox.Show("Entry posted"); 
        DataTemplate tmpl = (DataTemplate)this.FindResource("DefaultDataTemplate"); 
        listBox1.ItemTemplate = tmpl; 
       } 
      } 
      else 
      { 

       //Already synced.. Make a noise or something 
       System.Windows.MessageBox.Show("Already Synced;TODO Play a Sound Instead"); 
      } 
     } 


    } 

    private void EditButton_Click(object sender, RoutedEventArgs e) 
    { 
     if (EditButton.Content == "Edit") 
     { 
      listBox1.ItemTemplate = (DataTemplate)this.FindResource("EditableDataTemplate"); 
      EditButton.Content = "Done Editing"; 
     } 
     else 
     { 
      foreach (Harvest_TimeSheetEntry item in listBox1.Items) 
      { 
       Globals._globalController.harvestManager.updateHarvestTimeSheetEntry(item); 
       if (!item.isSynced) 
       { 
        if (ValidateEntry(item)) 
        if (IsValidTime(StartValue.ToString()) && IsValidTime(EndValue.ToString())) 
        Globals._globalController.harvestManager.postHarvestEntry(item); 
        System.Windows.MessageBox.Show("Entry posted"); 
       } 

      } 
      EditButton.Content = "Edit"; 
      listBox1.ItemTemplate = (DataTemplate)this.FindResource("DefaultDataTemplate"); 
     } 
    } 

    private bool ValidateEntry(Harvest_TimeSheetEntry ent) 
    { 
     bool IsValid = true; 

     if (ent.ClientNameBinding == null || ent.TaskNameBinding == null || ent.ProjectNameBinding == null) throw new ArgumentNullException(); 
     { 
      IsValid = false; 
     } 

     return IsValid; 
    } 

    public bool IsValidTime(string time) 
    { 
     Regex checktime = 
      new Regex(@"^(20|21|22|23|[01]d|d)(([:][0-5]d){1,2})$"); 

     return checktime.IsMatch(time); 
    } 

    private void CustomButton_Click(object sender, RoutedEventArgs e) 
    { 
     Globals.ni2.Visible=false; 
     CustomView c = new CustomView(Globals._globalController.getDayViewWindow); 
     c.Show(); 
     this.Hide(); 
     Globals.ni3.Visible = true; 
    } 

    public void OnPropertyChanged(String time) 
    { 
     if (System.String.IsNullOrEmpty(time)) 
     { 
      return; 
     } 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(time)); 
     } 
    } 

    #region INotifyPropertyChanged Members 
    public event PropertyChangedEventHandler PropertyChanged; 
    #endregion 
} 

我想設置日期和時間他們。我知道如果它們不在DataTemplate中,下面兩行將爲它們設置日期和時間。

StartPicker.Value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,DateTime.Now.Minute,DateTime.Now.Second); 
EndPicker.Value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); 

因爲這些TimePickers在DataTemplate中,所以這些在我的代碼後面是不可訪問的。任何人都可以在這種情況下提出一些設置日期和時間的方法嗎?

+0

使用數據綁定與屬性..檢查谷歌它.. – loop

+0

是你的組合框工作.. – loop

+0

是的。 ComboBox正在工作。 – user2622971

回答

0

我想我得到的解決方案實際上是在這裏發生的是這樣的。你有你的ListBox.ItemsSource屬性設置爲某些列表或集合讓你ListBoxItem中的DataContext被設置到這個列表,因此其EditableDataTemplate包含TimePicker在列表中搜索其結合特性(在startValue和endValue值)或收集,但實際上這些屬性是名單之外或在您的page.cs.so你必須設置的的RelativeSource財產TimePIcker這樣的..

<DataTemplate x:Key="sample" > 
     <xctk:TimePicker Name="StartPicker" Value="{Binding DateTime, Mode=TwoWay,RelativeSource={RelativeSource AncestorType={x:Type Window}}}" Format="Custom" FormatString="hh:mm tt" Background="Yellow" Padding="0" Margin="0" BorderThickness="0" Width="100" EndTime="11:59:0"/> 
    </DataTemplate> 

如果你希望所有日e項目的startTime和EndTime不同,然後創建一個包含StartTime和EndTime屬性的獨立類。並列出這些對象,並將該列表綁定到您的列表框..hope你得到這個..對我的英文不好。

+0

我做了同樣的事情。但TimePicker值不會更新。 – user2622971

+0

你有沒有實現inotifypropertychanged – loop

+0

是的。我實現了inotifypropertychanged。 – user2622971

相關問題