我已经将WPF Datagrid的itemsource设置为从DAL返回的对象列表。我还添加了一个额外的列,其中包含一个按钮,下面是xaml。
<toolkit:DataGridTemplateColumn MinWidth="100" Header="View">
<toolkit:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Click="Button_Click">View Details</Button>
</DataTemplate>
</toolkit:DataGridTemplateColumn.CellTemplate>
</toolkit:DataGridTemplateColumn>
这样渲染效果很好。但是,在Button_Click方法中,有没有什么方法可以获取按钮所在的datagrid上的行?更具体地说,我的对象的属性之一是"Id",我希望能够将其传递到事件处理程序中的另一个窗体的构造函数中。
private void Button_Click(object sender, RoutedEventArgs e)
{
//I need to know which row this button is on so I can retrieve the "id"
}
也许我在我的xaml中需要一些额外的东西,或者我正在以一种间接的方式来做这件事?如有任何帮助/建议,敬请惠顾。
发布于 2009-07-23 02:15:24
基本上,您的按钮将继承行数据对象的datacontext。我把它叫做MyObject,希望MyObject.ID就是你想要的。
private void Button_Click(object sender, RoutedEventArgs e)
{
MyObject obj = ((FrameworkElement)sender).DataContext as MyObject;
//Do whatever you wanted to do with MyObject.ID
}
发布于 2011-02-08 04:37:28
我喜欢的另一种方法是将ID绑定到按钮的CommandParameter属性:
<Button Click="Button_Click" CommandParameter="{Binding Path=ID}">View Details</Button>
然后你可以像这样在代码中访问它:
private void Button_Click(object sender, RoutedEventArgs e)
{
object ID = ((Button)sender).CommandParameter;
}
发布于 2013-11-15 18:17:26
另一种方式是绑定到命令参数DataContext,并像Jobi Joy说的那样尊重MVVM,按钮继承datacontext形式的行。
XAML中的按钮
<RadButton Content="..." Command="{Binding RowActionCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"/>
命令实现
public void Execute(object parameter)
{
if (parameter is MyObject)
{
}
}
https://stackoverflow.com/questions/1168976
复制相似问题