简体   繁体   中英

How to format a System.Windows.Media.Color in XAML using StringFormat

I need to present System.Windows.Media.Color in a TextBlock formatted as hexadecimal #rrggbb . Binding a color like

<TextBlock Text="{Binding Color}"/>

results in a string formatted like #aarrggbb . I know I could create my own converter to get the desired format, but I don't like the effort. I wondered if there is no other, much simpler way.

I know, defining formats of a DateTime could be easily done like

StringFormat={}{0:HH:mm}

Similar to this solution I tried

StringFormat={}{0:#rrggbb}

but the result is

sc#1rrggbb, rrggbb, 1rrggbb, 1rrggbb

Is there a way to use StringFormat to format the color? If yes, whats the corret syntax?

Pure xaml solution. Note that Run tags should be in one line or you get whitespaces between rgb values.

<TextBlock DataContext="{Binding Color}" Text="#">
    <Run Text="{Binding R, StringFormat={}{0:X}}"/><Run Text="{Binding G, StringFormat={}{0:X}}"/><Run Text="{Binding B, StringFormat={}{0:X}}"/>
</TextBlock>

Finally, after searching a lot, I think it's not possible to format a Color as simple as a DateTime . My solution requires a few lines more but basically it's the same. Using MultiBinding it's possible to put the formatted color values together like:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="#{0:X2}{1:X2}{2:X2}">
            <Binding Path="Color.R"/>
            <Binding Path="Color.G"/>
            <Binding Path="Color.B"/>
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

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