我是XMAL的新手,但已经设法凑齐了一个从SQL检索数据并填充数据网格的表单。为了扩展这个,我想只根据两个日期返回数据。我创建了一个方法GetAllActionLogsBetweenDates(),它接受两个属性QueryFromDate,QueryToDate。
单击FindButton时,我需要将日期选择器中的2个日期传递给GetAllActionLogsBetweenDates方法。
我的XAML看起来像这样
<StackPanel Height="114"
Orientation="Vertical"
HorizontalAlignment="Left"
Name="StackPanel1"
VerticalAlignment="Top"
Width="507">
<DatePicker Height="25"
SelectedDate="{Binding QueryFromDate, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="115"
x:Name="DateFrom"
Margin="5"/>
<DatePicker Height="25"
SelectedDate="{Binding QueryToDate, Mode=TwoWay}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="115"
Margin ="5 "
x:Name="DateTo"/>
<Button Content="Find"
x:Name="FindButton"
Command="{Binding ?????}"
Height="23"
Margin="5"
Width="75"
HorizontalAlignment="Left" />
</StackPanel>
我想我必须在Command =“{Binding ?????}”元素中做一些引用我的方法的东西,大概是2个属性QueryFromDate,QueryToDate但是我不确定是什么
谢谢
答案 0 :(得分:0)
如果您正在使用ViewModel,则需要实现ICommand
并在ViewModel类中创建一个Command。
此问题有一个您可以使用的示例实现:How to bind WPF button to a command in ViewModelBase?
或者,如果您只是使用代码隐藏(.xaml.cs),则可以使用Click
事件:
<Button Content="Find" Click="FindClicked" />
然后,您将FindClicked
方法添加到代码隐藏中:
void FindClicked(object sender, RoutedEventArgs e) { }
答案 1 :(得分:0)
如果您正在使用MVVM,首先需要定义实现RelayCommand
的{{1}}对象,如下所示:
ICommand
然后,您需要在ViewModel中为按钮创建命令。像这样:
public class RelayCommand : ICommand
{
private Predicate<object> m_canExecute;
private Action<object> m_execute;
public RelayCommand(Action<object> execute)
{
m_execute = execute;
}
public RelayCommand(Predicate<object> canExecute, Action<object> execute)
{
m_canExecute = CanExecute;
m_execute = execute;
}
public bool CanExecute(object parameter)
{
if (m_canExecute == null)
{
return true;
}
return m_canExecute(parameter);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (m_execute != null)
{
m_execute(parameter);
}
}
}
现在,由于您要将多个参数传递给命令,因此可以使用public class MainViewModel : INotifyPropertyChanged
{
// INotifyPropertyChanged implementation
public ICommand GetAllActionLogsBetweenDatesCommand { get; set; }
public MainViewModel()
{
GetAllActionLogsBetweenDatesCommand = new RelayCommand(GetAllActionLogsBetweenDates_Execute);
}
private void GetAllActionLogsBetweenDates_Execute(object parameter)
{
try
{
var stringList = parameter as string[];
DateTime fromDate = DateTime.Parse(stringList[0]);
DateTime toDate = DateTime.Parse(stringList[1]);
// Query the data.
}
catch (Exception ex)
{
}
}
}
来选择两个日期并将其传递给ViewModel。这就是转换器的样子:
IMultiValueConverter
最后,在您的XAML中,您创建了此转换器的实例并将其绑定到您的按钮:
public class ICommandMultiDateConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new string[] { values[0].ToString(), values[1].ToString() };
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}