【发布时间】:2020-06-23 23:43:52
【问题描述】:
我有一个带有 GroupStyle 的数据网格,里面有一个扩展器。由于我的应用程序的性质,我需要动态创建 Expander 的内容,因此我放置了一个事件 Onloaded 来创建列。 这是代码:
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander x:Name="exp" Loaded="OnLoaded" Background="#dedede" HorizontalAlignment="Left" HorizontalContentAlignment="Left" PreviewMouseLeftButtonUp="Expander_MouseDown" BorderThickness="0 0 0 1" BorderBrush="#d0d0d0" Padding="2,0,0,0" Style="{StaticResource StatusGroupExpanderStat}">
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
背后的代码:
private void OnLoaded(object sender, RoutedEventArgs e)
{
StackPanel stackPanel = new StackPanel();
stackPanel.Orientation = Orientation.Horizontal;
stackPanel.Height = 30;
Expander exp = sender as Expander;
string currDate = ((dynamic)exp.DataContext).Name;
// Espando il primo Expander
Statistic statRec = BaseData.FirstOrDefault();
if (statRec != null)
exp.IsExpanded = statRec.Data == currDate && exp.IsExpanded;
// Item da usare per valorizzare le colonne
Statistic statItem = BaseDataParents.FirstOrDefault(d => d.Data == currDate);
// Ciclo per creare le colonne
foreach (var column in GridData.Columns.Where(c => !String.IsNullOrEmpty(c.Header.ToString())))
{
DataGridColumn col = GridData.Columns.FirstOrDefault(c => c.Header != null && c.Header.ToString() == column.Header.ToString());
if (col == null) continue;
TextBlock textBlock = new TextBlock
{
Width = col.ActualWidth,
Padding = new Thickness(13, 8, 0, 2),
Text = FormatValue(statItem, GetColumnNameByKey(column.Header.ToString())),
Style = this.FindResource("HeaderTextBlock") as Style,
ToolTip = FormatValue(statItem, GetColumnNameByKey(column.Header.ToString()))
};
stackPanel.Children.Add(textBlock);
}
exp.Header = stackPanel;
}
基本上,我注意到在 evetytime 我折叠了一个扩展器,触发了 OnLoaded 事件并重新创建了我的列;我不想要这种行为,有机会吗?
【问题讨论】:
-
用扩展事件docs.microsoft.com/en-us/dotnet/api/…代替OnLoaded事件怎么样?