Search code examples
c#wpfimagebuttondynamicresource

Button default content if image (from dynamic resource) is not available


In a UserControl, I want the buttons to show images (provided by dynamic resources). If the dynamic resource is not available / provided by the application, I want the button to show some default content.

My idea was to put the default content into a textblock that is located underneath the image and hide it (so it does not shine through) as long as the image source is null. But this condition does not seem to work if resolving the DynamicResource fails. What exactly would be the status of the image's source in that case?

<Button Command="{Binding DoSomethingCommand}">
  <Grid>
    <TextBlock Text="DefaultText" Visibility="Collapsed">
         <TextBlock.Style>
           <Style TargetType="TextBlock">
            <Style.Triggers>
              <DataTrigger Binding="{Binding ElementName=TestImage, Path=Source}" Value="{x:Null}">
                 <Setter Property="Visibility" Value="Visible"></Setter>
              </DataTrigger>
            </Style.Triggers>
           </Style>
          </TextBlock.Style>
    </TextBlock>
    <Image x:Name="TestImage" Source="{DynamicResource SomeResource}" Stretch="None"/>
    </Grid>
  </Button>

What would be a proper solution?

Thanks for your help!


Solution

  • Try this:

        <Button Command="{Binding DoSomethingCommand}">
            <Grid>
                <TextBlock Text="DefaultText" />
                <Image x:Name="TestImage" Source="{DynamicResource SomeResource}" Stretch="None"/>
            </Grid>
        </Button>
    

    The TextBlock will be hidden by the Image only when the resource lookup succeeds.

    The problem with this is, that the default content shines through if the image is showing and it does not cover the entire default content

    What about this then?

        <Button Command="{Binding DoSomethingCommand}">
            <Grid>
                <Image x:Name="TestImage" Source="{DynamicResource SomeResource}" Stretch="None"/>
                <TextBlock Text="DefaultText">
                    <TextBlock.Style>
                        <Style TargetType="TextBlock">
                            <Setter Property="Visibility" Value="Collapsed" />
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding Path=Source, ElementName=TestImage}" Value="{x:Null}">
                                    <Setter Property="Visibility" Value="Visible" />
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </TextBlock.Style>
                </TextBlock>
            </Grid>
        </Button>