I have code that is supposed to add textblocks to a stack panel that is already created in xaml. I then want to surround that stack panel by an extender. However, the expander is not showing up when I run it at all.
code to add to textblocks (a list of exceptions):
public void Update(AggregateException ae)
{
StackPanel exceptionsSP = this.ExceptionSP;
Expander exceptionExpander = new Expander();
exceptionExpander.Name = "Exceptions";
exceptionExpander.Header = ae.Message;//The outer exception message
exceptionExpander.IsExpanded = false;
exceptionExpander.ExpandDirection = ExpandDirection.Down;
List<TextBlock> exceptionTexts = new List<TextBlock>();
foreach (Exception exception in ae.InnerExceptions)
{
TextBlock textBlock = new TextBlock();
textBlock.Text = exception.Message;
exceptionsSP.Children.Add(textBlock);
}
exceptionExpander.Content = exceptionsSP;
}
XAML already created:
<Grid.RowDefinitions>
<RowDefinition Height="300"/>
<RowDefinition x:Name="OKButton" Height="111"/>
</Grid.RowDefinitions>
<StackPanel x:Name="ExceptionSP" Grid.Row="0">
</StackPanel>
<Button Grid.Row="1" IsCancel="True" VerticalAlignment="Center" Width="50" Height="30"/>
Resulting xaml (No Extender):
CodePudding user response:
You are creating the expander in code and then setting the expander's content to the StackPanel that is created in XAML. That doesn't make any sense...the Expander just goes away at the completion of your function. The expander needs to be created in XAML, or you need some sort of ContentPresenter in the XAML to hold the Expander.
Without editing the XAML you could: Ceate a new inner StackPanel, add the items to that, set that as the content for the expander, then finally do this.ExceptionSP.Content = exceptionExpander
.
This is what the code would look like if you didn't want to change your XAML
public void Update(AggregateException ae)
{
StackPanel innerSp = new();
Expander exceptionExpander = new Expander();
exceptionExpander.Name = "Exceptions";
exceptionExpander.Header = ae.Message;//The outer exception message
exceptionExpander.IsExpanded = false;
exceptionExpander.ExpandDirection = ExpandDirection.Down;
List<TextBlock> exceptionTexts = new List<TextBlock>();
foreach (Exception exception in ae.InnerExceptions)
{
TextBlock textBlock = new TextBlock();
textBlock.Text = exception.Message;
innerSp.Children.Add(textBlock);
}
exceptionExpander.Content = innerSp;
this.ExceptionSP.Content = exceptionExpander;
}