我有一个如下的WPF按钮:
<Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button>
我想把{Binding Code}
作为参数传递给处理程序,该怎么做呢?
免责声明:我对WPF非常陌生。
<Button Tag="{Binding Code}" ...>
sender
对象转换为Button
并访问Tag
属性:var myValue = ((Button)sender).Tag;
更加优雅的解决方案是使用WPF的命令模式:为您想要按钮执行的功能创建一个命令,将该命令绑定到按钮的Command
属性上,并将CommandParameter
绑定到您的值。
我不是太喜欢“标签”,因此也许
<Button Click="button1_Click" myParam="parameter1" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button>
然后通过属性访问。
void button1_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var theValue = button.Attributes["myParam"].ToString()
}
有两种方法可以做到这一点:
将DataContext进行强制转换(Cast)
void button1_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var code = ((Coupon)button.DataContext).Code;
}
或者使用Tag属性,这是一个通用的状态属性。
<Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Tag="{Binding Code}" />
那么。void button1_Click(object sender, RoutedEventArgs e)
{
var button = sender as Button;
var code = button.Tag;
}
(Button)sender
而不是sender as Button
。即使在极少情况下sender
不是一个按钮,(Button)sender
将抛出一个InvalidCastException异常,这有助于您找到错误。另一方面,您的代码将在这种情况下悄无声息地将button
设置为null,从而导致稍后发生NullReferenceException异常。 - Heinzi使用 Xaml 和 DataContext
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:DataAndCloudServices"
x:Class="DataAndCloudServices.MainPage" >
<StackLayout>
<!-- Command Implemented In Code Behing -->
<Button Text="Consuming Web Services Samples"
Command="{Binding NavigateCommand}"
CommandParameter="{x:Type local:YourPageTypeHere}" >
</Button>
</StackLayout>
</ContentPage>
在 MainPage Code Behind 中,这个代码示例是使用页面类型作为参数导航到另一个页面,您需要创建 "YourPageTypeHere" 并在此引用页面。
然后实现 Code Behind。
using System;
using System.Windows.Input;
using Xamarin.Forms;
namespace DataAndCloudServices
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
NavigateCommand = new Command<Type>(
async (Type pageType) =>
{
Page page = (Page)Activator.CreateInstance(pageType);
await Navigation.PushAsync(page);
});
this.BindingContext = this;
}
public ICommand NavigateCommand { private set; get; }
}
}
同时在你的App类中,需要在MainPage中创建一个NavigationPage实例来进行导航(以本示例为例)
public App ()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
这是针对Xamarin Forms的,但是WPF项目也类似。
命令可用于WPF和Xamarin: "https://dev59.com/2o3da4cB1Zd3GeqP37vC#47887715"