Search code examples
c#wpfdata-binding

Bind and render Visual property in WPF XAML


I think I am struggling with something really basic, but I cannot find a way to bind and render a 'Visual' type property.

In my model, I have a list of user names, along with a Identicon rendered by this nice library.

https://jdenticon.com/net-api/M_Jdenticon_WpfExtensions_ToVisual.html

For WPF it provides a .ToVisual() extension method, however I don't know how to make that 'Visual' appear in the UI. I tried several approaches such as Rectangle.Fill, Paths, ContentPresenters etc.

In general, the binding looks as follows - the UserIcon is a property of type Visual.

 <CheckBox.Content>
                                    <Grid Margin="0,2" >
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="16" />
                                            <ColumnDefinition Width="120" />
                                        </Grid.ColumnDefinitions>
                                        <Image Grid.Column="0" Source="{Binding User.UserIcon}"></Image>
                                        <TextBlock Grid.Column="1" Text="{Binding User.Name}" Margin="3,0"/>
                                    </Grid>
                                </CheckBox.Content>

How do I render this?


Solution

  • You may use a VisualBrush:

    <Rectangle Width="100" Height="100">
        <Rectangle.Fill>
            <VisualBrush Visual="{Binding User.UserIcon}"/>
        </Rectangle.Fill>
    </Rectangle>