简体   繁体   中英

Remove white spaces between C# Flowdocument elements?

I would like to be able to remove the white spaces between various inline elements of a FlowDocument. Below is a very specific example just to make the problem clear. The desired output is "Hello World?" but what happens is "Hello World ?". In this case "?" is a clickable button.

I have searched for a while without success. I tried all forms of pad/margin adjustment, but they can only increase the spacing. I am beginning to believe the space is inherent to FlowDocument element boundaries. This seems like a series limitation.

<RichTextBox>
  <FlowDocument>
    <Paragraph Margin="0">
      <Run>
        Hello World
      </Run>
      <InlineUIContainer>
        <Button Click="ButtonClick">?</Button>
      </InlineUIContainer>
    </Paragraph>
  </FlowDocument>
</RichTextBox>

As ugly as the formatting might seem, in XML based XAML, if you want to avoid whitespace between runs you cannot allow any space between the close and open tags of the elements. Try this:

<RichTextBox>
  <FlowDocument>
    <Paragraph Margin="0">
      <Run>
         Hello World
       </Run><InlineUIContainer>
           <Button Margin="0" >?</Button>
       </InlineUIContainer>
    </Paragraph>
  </FlowDocument>
</RichTextBox>

Ok, this problem is beacuse of special whitespace handling rules.

Idea of the solution : Preprocess xaml removing new line/whitespace characters between the tags.

Implementation :

  1. Move your Paragraph to a ResourceDictionary (for example Strings.xaml).
  2. Set "Build Action" for Strings.xaml to "Resource" (so it would be stored as text, not binary).
  3. Load it, remove whitespaces using the following code:

     var uri = @"pack://application:,,,/YourProjectName;component/PathToDictionary/Strings.xaml"; var resourceInfo = Application.GetResourceStream(uri); using (var xmlReader = new XmlTextReader(resourceInfo.Stream) { WhitespaceHandling = WhitespaceHandling.None}) { var xamlReader = new System.Windows.Markup.XamlReader(); dictionary = (ResourceDictionary)xamlReader.LoadAsync(xmlReader); } 
  4. Add the resource dictionary to the resources of the entity, wich should use the Paragraph:

     MyControl.Resources.MergedDictionaries.Add(dictionary); 
  5. That`s all, no additional Runs with whitespaces inside will be created.

I`m using our own custom localizable ResorceDictionary descendant, wich has an option to remove whitespaces and is processing all this stuff automatically.

您可以在按钮上添加负边距以使其更接近:

<InlineUIContainer><Button Margin="-3,0">?</Button></InlineUIContainer>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM