0

I am attempting to add an expander from code behind to an existing ListBox. The content that needs to be displayed in the header of the expander comes from a directory name which may or may not contain underscores. I want to preserve the directory name and not have the first underscore be interpreted as a keyboard shortcut.

I found this thread discussing how to do it in xaml and have tried to implement the same solution in code behind without any luck.

I also found this thread discussing how to create a data template from the code behind, but I can't get that to work either.

I have tried the following code snippets but either it won't compile or it just displays blanks for the expander headers:

String markup = String.Empty;
markup = "<TextBlock text=\"" + directory.Name + "\"/>";
ex.HeaderTemplate = new DataTemplate((DataTemplate)XamlReader.Load(markup));

.

ex.HeaderTemplate = new DataTemplate("TextBlock");
TextBlock tb = new TextBlock();
tb.Text = directory.Name;
ex.Header = tb;
Chris
  • 402
  • 1
  • 5
  • 18
  • 1
    https://stackoverflow.com/questions/40733/disable-wpf-label-accelerator-key-text-underscore-is-missing – ASh Sep 05 '19 at 13:06
  • 1
    @ASh ah, thanks. I didn't realize I could assign the header to a TextBlock object. That's way simpler than what I was trying to do. – Chris Sep 05 '19 at 13:14

1 Answers1

1

you don't need to change HeaderTemplate to avoid underscore conversion into AccessKey.

add TextBlock into Expander.Header explicitly, and it will keep text unchanged.

<Expander>
    <Expander.Header>
        <TextBlock x:Name="ExpanderHeader"/>
    </Expander.Header>
</Expander>

this way you don't need to create UI elements in c# code.

change header text in ExpanderHeader textBlock

ExpanderHeader.Text = directory.Name;

or bind it if there is a view model:

<TextBlock x:Name="ExpanderHeader" Text="{Binding Path=...}"/>
ASh
  • 34,632
  • 9
  • 60
  • 82