我试图在我的UWP应用程序中与microsoft . xam . interactivity在ListView中附加一个事件处理程序。当我在ListView中选择一行时,应用程序根据选中的项执行一个过程。
所以,我已经安装了" microsoft . xml . behaviors . uwp . managed "并将XAML文件更改为如下所示:
<ListView VerticalAlignment="Stretch"
x:Name="listBoxobj"
HorizontalAlignment="Stretch"
Margin="10,0,0,10"
Background="White"
Foreground="Black"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ItemsSource="{Binding Tools}"
SelectedItem= "{Binding SelectedItem, Mode=Twoway}"
SelectionMode="Single">
<Interactivity:Interaction.Behaviors>
<Interactions:EventTriggerBehavior EventName="ItemClick" SourceObject="listBoxObj">
<Interactions:InvokeCommandAction Command="{Binding Tool_Clicked}" CommandParameter="{Binding SelectedItem}" />
</Interactions:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
并在其ViewModel中实现了以下内容:
private System.Windows.Input.ICommand tool_Clicked;
public ICommand Tool_Clicked
{
get {
return tool_Clicked;
}
set {
if (!Object.ReferenceEquals(tool_Clicked, value))
{
tool_Clicked = value as RelayCommand;
OnPropertyChanged("Tool_Clicked");
}
}
}
public DisplayViewModel()
{
...
Tool_Clicked = new RelayCommand(SelectionChanged);
...
}
public void SelectionChanged(object arg) {
... executes some procedures according to the selected item...
}
但是当我测试这些代码时,发出了以下异常:系统。typeeloadexexception: '无法找到Windows运行时类型' system .Windows. input . iccommand '.'
另一方面,在Debug模式下,没有抛出这样的异常。所以,我有两个问题:- 我想知道调试模式和发布模式有什么区别。 是否有任何方法可以避免抛出system . typeloadeexception ?
更新1:我已经在发布模式下配置了编译选项。
- 我已经检查了"编译与。net原生工具链">
- 我已经检查了"不安全代码"。
但是当我试图构建我的项目时,它已经以以下错误消息结束:错误:MCG0018:TypeExpected类型文件或程序集System.Runtime.InteropServices.WindowsRuntime。PropertyType' not found.
当我试着取消勾选"用。net原生工具链编译"时,我可以运行这段代码。我认为我使用的一些nuget包不支持。net本地代码…
更新2:
我创建了RelayCommand类,如下所示:
public class RelayCommand : ICommand
{
private readonly Action<Object> _execute;
private readonly Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged;
public RelayCommand(Action<object> execute) :
this(execute, null)
{ }
public RelayCommand(Action<object> execute, Func<object, bool> canExecute)
{
_execute = execute ?? throw new ArgumentNullException("execute");
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
我注意到你的问题已经在Microsoft Q&A-System上解决了。typeeloadeexception在发布模式中由Nico发生。
为了使Nico的回答简短,您可以使用Tapped
事件而不是使用click
事件。然后可以使用当前数据上下文作为参数
代码如下:
<DataTemplate>
<TextBlock Text="{Binding}">
<Interactivity:Interaction.Behaviors>
<Interactions:EventTriggerBehavior EventName="Tapped">
<Interactions:InvokeCommandAction Command="{Binding ElementName=listBoxObj, Path=DataContext.Tool_Clicked}" CommandParameter="{Binding}" />
</Interactions:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</TextBlock>
</DataTemplate>