【问题标题】:WPF Expander event behaviorWPF 扩展器事件行为
【发布时间】: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 事件并重新创建了我的列;我不想要这种行为,有机会吗?

【问题讨论】:

标签: c# wpf datagrid expander


【解决方案1】:

您可以处理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;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 1970-01-01
    • 2019-06-14
    • 2013-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多