我有一个Silverlight 5项目,它有一个Styles.xaml和另一个类,我在运行时创建了一个DataGrid。我想在DataGridColumnHeader中有一些按钮来实现某种过滤功能。样式定义如下:
<Style x:Key="DataGridFilterStyle" TargetType="sdk:DataGridColumnHeader">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<Grid Height="{TemplateBinding Height}" Width="Auto">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0.2"/>
<Button Content="Foo" Margin="5,0" x:Name="filter" />
</StackPanel>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
然后,我在运行时生成一个DataGrid。我不知道父页面,因为它是通用的:
dg = New DataGrid
dg.AutoGenerateColumns = False
dg.RowHeight = 28
' Doing some stuff here....
dg.ColumnHeaderStyle = Application.Current.Resources("DataGridFilterStyle")
gd.Children.Add(dg) ' gd is a Grid as a parent container
所以,我有我的Styles.xaml和一个单独的类,我在其中做一些事件。如何将单击事件添加到DataGridColumnHeader(筛选器)中的按钮?通常情况下,如果样式和代码在同一个文件中,也不会有问题。
谢谢你的帮助!
问候
Daniel
<StackPanel Orientation="Horizontal" Margin="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<TextBlock Text="{Binding}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0.2"/>
<Button Content="Foo" Margin="5,0" x:Name="filter" Click="filter_Click" /> //xaml
</StackPanel>
private void filter_Click(object sender, RoutedEventArgs e) //code behind
{
}
我希望这将有助于
您可以在设置数据网格头样式的代码中获得按钮控件。您需要首先删除TemplateBindingHeight="{TemplateBinding Height}"
下面是在代码后面获取按钮控件的代码。
var style = Application.Current.Resources["DataGridFilterStyle"] as Style;
dataGrid1.ColumnHeaderStyle = style;
style = dataGrid1.ColumnHeaderStyle;
var setter = style.Setters.FirstOrDefault();
var k = setter as Setter;
var val = k.Value as DataTemplate;
var obj = val.LoadContent() as Grid;
var button = (obj.Children[0] as StackPanel).Children[1];
希望这能解决你的问题。
干杯!Vinod