-1

I have views that may or may not be created in xaml based on a boolean condition in codebehind or a viewmodel.

I'd like to do something like:

<AlwaysVisibleView />

<IfShowSometimesViewBindingOrVariableOrSomething>
<SometimesView AProperty="something"/>
</IfShowSometimesViewBindingOrVariableOrSomething>

I'd like to implement this avoiding codebehind and other such trickery as much as possible, at the last ideally I don't want the view to be instantiated.

Noam M
  • 3,156
  • 5
  • 26
  • 41
meds
  • 21,699
  • 37
  • 163
  • 314
  • You can use a ContentPresenter, see answers for https://stackoverflow.com/questions/9359364/datatrigger-on-contentpresenter-content-not-working This solution should probably only be used when you may change the property during runtime. I guess that attaching a child in codebehind is fine if the control doesn't change during runtime. – Dennis Kuypers Jun 29 '17 at 00:57

2 Answers2

1

Dynamic creation of views can sometimes get a little tricky. Plus they tend to mess up how XAML renders things.

Can you just bind the visibility of the "Sometimes visible view" to a property? You can run that through a Boolean to visibility convertor and just have the code behind toggle the bool to show/hide.

Example thread

Frank Sposaro
  • 8,511
  • 4
  • 43
  • 64
1

You can work with ContentControl and Style.Triggers to change content and visibility based on a property (example: bool ShowMe):

<ContentControl>
    <ContentControl.Style>
        <Style TargetType="ContentControl">
            <Setter Property="Content" Value="{x:Null}"/>
            <Setter Property="Visibility" Value="Collapsed"/>
            <Style.Triggers>
                <DataTrigger Binding="{Binding ShowMe}" Value="True">
                    <Setter Property="Content">
                        <Setter.Value>
                            <SometimesView AProperty="something"/>
                        </Setter.Value>
                    </Setter>
                    <Setter Property="Visibility" Value="Visible"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>
grek40
  • 13,113
  • 1
  • 24
  • 50