WPF 扩展器事件行为

WPF Expander event behavior

我有一个带有 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;
}

基本上我注意到我每次折叠扩展器时都会触发事件 OnLoaded 并重新创建我的列;我不想要这种行为,有机会吗?

您可以处理 Expanded 事件并可能使用 bool 字段来确定 Expander 是否已经初始化一次:

private bool _isInitialized;
private void exp_Expanded(object sender, RoutedEventArgs e)
{
    if (!_isInitialized)
    {
        StackPanel stackPanel = new StackPanel();
        stackPanel.Orientation = Orientation.Horizontal;
        stackPanel.Height = 30;
        ...

        _isInitialized = true;
    }
}