[英]WP8 Databind button click/Command with RoutedEventHandler
Fairly new to Windows Phone and Xaml and I decided to start using the DataTemplates as it looked neater and I could easily switch them etc. Windows Phone和Xaml相当新,我决定开始使用DataTemplates,因为它看起来更整洁,我可以轻松切换它们等。
I have a requirement where on a button click depending on the data on the item in the list I want to call a different function or with different parameters. 我有一个要求,按钮点击取决于列表中项目的数据,我想调用不同的功能或不同的参数。 I thought the easiest way would be to bind a RoutedEventHandler to it via an anonymous function. 我认为最简单的方法是通过匿名函数将RoutedEventHandler绑定到它。
When I did this in code-behind with static controls on the formed it worked perfectly. 当我在代码隐藏中使用静态控件执行此操作时,它完美地工作。 It also worked when I added my own controls to a stack panel etc. But it was all quite messy. 当我将自己的控件添加到堆栈面板等时,它也有效。但它都非常混乱。
// Example of RoutedEventHandler that works when I create the button in code behind
model.clickEventHandler = (s, e) => LoadResult(r.id);
<ScrollViewer Name="scrvResults" >
<ListBox Name="lbResults" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<Button Command="{Binding clickEventHandler}" >
// Stuff
// Doesn't crash but doesn't fire the event
</Button>
<Button Click="{Binding clickEventHandler}" >
// Stuff
// Throws a com exception
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
I've tried various sub options. 我尝试了各种子选项。 All the examples i've seen seem to link to a static function. 我见过的所有例子似乎都链接到静态函数。 Is this just some syntax i'm getting wrong is can I not bind to it this way? 这只是一些语法,我错了,我不能这样绑定它吗?
You need to bind your command to a type of ICommand. 您需要将命令绑定到一种ICommand。 See here for more info: 有关详情,请参阅此处:
Button click event can be bound by using interaction triggers, not by simply binding the event to the click attribute: 可以使用交互触发器绑定按钮单击事件,而不是简单地将事件绑定到click属性:
Using EventTrigger in XAML for MVVM – No Code Behind Code 在XAML中为MVVM使用EventTrigger - 代码背后没有代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.