在我的wpf应用程序中,我有两个timePicker控件,它们位于DataTemplate中。
的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="<---" 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中,所以在我的代码后面无法访问这些TimePickers。在这种情况下,有人可以建议一些设定日期和时间的方法吗?
答案 0 :(得分:0)
我认为我得到的解决方案实际上这里发生的是这个。您已将 ListBox.ItemsSource 属性设置为某个列表或集合,以便 ListBoxItem Datacontext 设置为此列表,因此其 EditableDataTemplate 包含< strong> TimePicker 在List或Collection中搜索其绑定属性(startValue和endValue),但实际上这些属性在List之外或在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>
如果您希望所有项目的startTime和EndTime不同,则创建一个包含StartTime和EndTime属性的单独类。并列出这些对象,并将该列表绑定到您的listBox ..希望你得到这个......我的英语不好