首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WPF Expander事件行为

WPF Expander事件行为
EN

Stack Overflow用户
提问于 2020-06-23 17:42:46
回答 1查看 123关注 0票数 0

我有一个带GroupStyle的datagrid,里面还有一个扩展器。由于我的应用程序的性质,我需要动态创建Expander的内容,因此我放入了一个事件,我在其中创建了列。代码如下:

代码语言:javascript
复制
<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>

后面的代码:

代码语言:javascript
复制
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都会被触发,我的列会被重新创建;我不想要这种行为,有没有机会这样做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-06-23 23:43:52

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

代码语言:javascript
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62531786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档