【发布时间】:2014-06-25 06:45:18
【问题描述】:
我是 C# 和 WPF 的新手,并且已经完成了编写警报的任务。现在我有一个问题,我必须在关闭主窗口时将设置的时间保存到一个文本文件中。
时间存储在 Reminder 类型的 ObservableCollection 中,这是我自己编写的一个类,并将警报的时间和名称存储为字符串。
public override string ToString()
{
return ReminderName + " " + ReminderTime.ToString("HH:mm");
}
我的保存功能是这样的:
...
public RelayCommand<object> SaveAllTimes { get; set; }
...
public MainWindowModel()
{
...
SaveAllTimes = new RelayCommand<object>(SaveReminders, CanSaveReminders);
...
}
private void SaveReminders(object sender)
{
StreamWriter writer = new StreamWriter("time.txt");
foreach (Reminder time in Reminders)
{
writer.WriteLine(time.ToString());
}
}
现在我怎样才能将视图绑定到这个函数,当用户关闭它时它会被执行?
我的观点是这样的:
<Window x:Class="Wecker1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Wecker1"
Height="350"
Width="310" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="3*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<ListBox Name="Liste" ItemsSource="{Binding Reminders}" Margin="10" Grid.Row="0">
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding}" IsChecked="{Binding Active}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding SaveTime}" Content="Add Reminder" Margin="10" Grid.Column="1"/>
<Button Margin="10" Content="Stop" Command="{Binding DeleteTime}"
CommandParameter="{Binding ElementName=Liste,Path=SelectedItem}" />
</Grid>
</Grid>
</Window>
【问题讨论】: