我有一个ListView,它将一个月中的所有日子显示为按钮,每个按钮包含日期。当我点击其中一个按钮时,我希望它能把我带到当天的视图。按钮命令绑定到ToDayView命令。我不想为可能是一个月的每一天做一堆不同的命令。如何使用命令传递日期?
MonthView
<ListView ItemsSource="{Binding CurrentMonth.Days}" Grid.Row="1">
<ListView.ItemTemplate>
<DataTemplate>
<Button Content="{Binding DayNumber}" Grid.Row="1" Height="20" Width="100"
Command="{Binding ToDayViewCommand}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
MonthViewModel
public class MonthViewModel : ViewModelBase
{
private readonly NavigationStore _navigationStore;
private Month _currentMonth;
public Month CurrentMonth
{
get { return _currentMonth; }
set
{
_currentMonth = value;
OnPropertyChanged("CurrenMonth");
}
}
public void ToDayView(object thing)
{
// use parameter as day number
int dayNumber = 25;
// find the Day object with that day number
for(int i = 0; i < CurrentMonth.Days.Count; i++)
{
if(CurrentMonth.Days[i].DayNumber == dayNumber)
{
// give it to the view model to be displayed
_navigationStore.CurrentViewModel = new DayViewModel(CurrentMonth.Days[i], _navigationStore);
}
}
}
public BasicCommand ToDayViewCommand { get; set; }
public MonthViewModel(Month currentMonth, NavigationStore navigationStore)
{
CurrentMonth = currentMonth;
_navigationStore = navigationStore;
ToDayViewCommand = new BasicCommand(ToDayView);
}
}
BasicCommand
public class BasicCommand : CommandBase
{
readonly Action<object> _execute;
public BasicCommand(Action<object> execute)
{
_execute = execute;
}
public override bool CanExecute(object parameter) => true;
public override void Execute(object parameter)
{
_execute.Invoke(parameter);
}
}
您可以在XAML代码中定义命令参数:
<Button Content="{Binding DayNumber}" Grid.Row="1" Height="20" Width="100"
Command="{Binding ToDayViewCommand}" CommandParameter="25" />
注意CommandParameter
是一个依赖属性,因此你也可以使用绑定:
<Button Content="{Binding DayNumber}" Grid.Row="1" Height="20" Width="100"
Command="{Binding ToDayViewCommand}" CommandParameter="{Binding AmountDays}" />
在命令调用的方法中,必须将对象强制转换为int类型。注意你的参数是一个字符串,如果你像我的第一个代码片段那样调用它,那么你必须使用int.Parse
:
public void ToDayView(object thing)
{
// use parameter as day number
int dayNumber = int.Parse(thing.ToString());
// find the Day object with that day number
for(int i = 0; i < CurrentMonth.Days.Count; i++)
{
if(CurrentMonth.Days[i].DayNumber == dayNumber)
{
// give it to the view model to be displayed
_navigationStore.CurrentViewModel = new DayViewModel(CurrentMonth.Days[i], _navigationStore);
}
}
}