我有这样一个wpf按钮:
<Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button>
我希望将作为参数传递的{Binding Code}
传递给button1_click处理程序。
我该怎么做?
免责声明: WPF非常新
发布于 2010-01-05 06:18:44
简单解决方案:
<Button Tag="{Binding Code}" ...>
在处理程序中,将sender
对象强制转换为Button
并访问Tag
属性:
var myValue = ((Button)sender).Tag;
更优雅的解决方案是使用WPF的命令模式:为按钮执行的功能创建一个命令,将命令绑定到button的Command
属性,并将CommandParameter
绑定到您的值。
发布于 2012-09-28 01:44:12
我不太喜欢“标签”所以也许
<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()
}
发布于 2018-06-29 08:25:30
使用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>
这个代码示例使用页面类型作为参数导航到另一个页面,您需要在这里创建"YourPageTypeHere“和引用页。
然后在后面实现代码。
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; }
}
}
同样,在应用程序类中,需要一个NavigationPage实例在MainPage中导航(对于本例来说)
public App ()
{
InitializeComponent();
MainPage = new NavigationPage(new MainPage());
}
它适用于xamarin表单,但对于WPF项目则类似。
命令可以更改为for WPF和Xamarin:"https://stackoverflow.com/a/47887715/8210755“。
https://stackoverflow.com/questions/2006507
复制