【发布时间】:2019-05-04 01:24:42
【问题描述】:
我正在尝试创建一个AutoSuggestBox,允许用户搜索特定的气象站。
为了处理 TextChanged 事件,我在标记中添加了到相应 ViewModel 属性的绑定:
<AutoSuggestBox Grid.Row="1"
PlaceholderText="Station"
VerticalAlignment="Center"
QueryIcon="Forward"
Width="300"
Height="50"
DisplayMemberPath="Name"
TextMemberPath="Name"
ItemsSource="{Binding Path=Stations}">
<i:Interaction.Behaviors>
<core:EventTriggerBehavior EventName="TextChanged">
<core:InvokeCommandAction Command="{Binding TextChanged}"></core:InvokeCommandAction>
</core:EventTriggerBehavior>
</i:Interaction.Behaviors>
</AutoSuggestBox>
我的 ViewModel 如下所示:
public class StationCollectionVM : INotifyPropertyChanged
{
private IStationManager stationManager;
private ICommand textChanged;
public ObservableCollection<StationVM> Stations { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public StationCollectionVM(IStationManager stationManager)
{
this.stationManager = stationManager;
Stations = new ObservableCollection<StationVM>();
LoadStations();
}
private async void LoadStations()
{
Stations.Clear();
IEnumerable<Station> stations = await stationManager.GetAllStationsAsync();
IEnumerator<Station> e = stations.GetEnumerator();
while (await Task.Factory.StartNew(() => e.MoveNext()))
{
Stations.Add(new StationVM(stationManager, e.Current));
}
}
public ICommand TextChanged
{
get
{
if (textChanged == null)
{
textChanged = new RelayCommand(args =>
{
// ICommand.Execute(...) takes only 1 param.
// How do you get both the AutoSuggestBox and
// AutoSuggestBoxTextChangedEventArgs param
// sent from the AutoSuggestBox?
// Filter stations based on the user input here...
});
}
return textChanged;
}
}
}
请注意RelayCommand 只是ICommand 的一个实现:
public class RelayCommand : ICommand
{
readonly Action<object> executeAction;
readonly Predicate<object> canExecutePredicate;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
executeAction = execute ?? throw new ArgumentNullException(nameof(execute));
canExecutePredicate = canExecute;
}
public void Execute(object parameter)
{
executeAction(parameter);
}
public bool CanExecute(object parameter)
{
return canExecutePredicate == null ? true : canExecutePredicate(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, new EventArgs());
}
}
如何访问StationCollectionVM 的TextChanged 属性中的两个事件参数?另外,将过滤后的电台列表传回 AutoSuggestBox 的首选方式是什么?
【问题讨论】: