Chaps et al,

After a few hours of experiments I have come to a waypoint decision on XAML
images. There is no *simple* one-liner way of using an image defined as
geometries in a XAML fragment. Tersely, for my mental records and in case
it helps others, here's what I found:

The image library provides images in this sample format where the outer
XAML defines a Viewbox

<Viewbox Width="16" Height="16" ...>
  <Rectangle Width="16 " Height="16">
    *<... resources and drawing elements ...>*
  </Rectangle>
</Viewbox>

I copied some XAML files into a Resources folder and set all their Build
Action to Resource. Unfortunately, a bit of convert code is required to
convert the XAML into an actal Viewbox to be added to the visual tree. This
is the core of my converter code:

string uri = $"Resources/{name}.xaml";
var stream = Application.GetResourceStream(new Uri(uri,
UriKind.Relative)).Stream;
var viewBox = (Viewbox)XamlReader.Load(stream);
viewBox.Height = double.NaN;
viewBox.Width = double.NaN;
return viewBox;

The Width and Height are *unset*, otherwise they always render at 16x16. I
then combine the resources and the convert in code like this, in a MenuItem
for example:

<MenuItem Header="_Open" Command="ApplicationCommands.Open">
  <MenuItem.Icon>
    <*ContentControl Content="{Binding Converter={StaticResource
AppConverter},ConverterParameter=FromXaml|OpenFolder}"*
Style="{StaticResource XamlIconStyle}"/>
  </MenuItem.Icon>
</MenuItem>

The bold bit is the trick. This all works as I hoped, and the menu icons
display nicely, and I can draw an image as 80x80 and it also displays
scaled and crisp:

[image: image.png]

*Good news* -- This is a neat way of adding scalable images to your app,
removing the need for sets of different sizes.

*Bad news* -- The WPF designer randomly shows an error after editing the
XAML as I did above. I sometimes see squiggly warning lines, but there is
nothing wrong. I often must click *reload the designer* link and it all
displays correctly again.

*Worse news* -- I used the XAML icons in TreeView nodes where there could
be large numbers of repeated icons, so I put them in a simple Dictionary
cache. A Viewbox can only be in one place in the visual tree, so each icon
appears in the tree once, making caching useless and producing this effect:

[image: image.png]

In summary, for now I will only use XAML images where I really need
scalable images, maybe inside Buttons, Toolbars or artwork. Otherwise I'll
stick to png for basic menus and tree nodes. I'm sure there are techniques
for efficiently using XAML images everywhere, but my attention span is
expiring.

*Greg K*
-- 
ozdotnet mailing list 
To manage your subscription, access archives: https://codify.mailman3.com/ 

Reply via email to