简体   繁体   中英

WPF - Control Template and control visibility based on data

I am using Control template to display listbox items. I want to set the visibility of the control based on the item value.

I need the same as How can I replace an image in a WPF grid with another control depending on the source data?

How to include this option in my code. (If the image source [ImgUrl] value is null i want to set the textblock [txtblkImg] visibility to collapse.)

My Code:

        <Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Padding" Value="2,0,0,0"/>
        <Setter Property="Template">
            <Setter.Value>                    
                <ControlTemplate TargetType="{x:Type ListBoxItem}">                       
                    <Grid Width="150">
                        <Grid.RowDefinitions>
                            <RowDefinition/>
                            <RowDefinition/>
                        </Grid.RowDefinitions>                           
                        <Image HorizontalAlignment="Center" Grid.Row="0" VerticalAlignment="Center"  x:Name="img" Source="{Binding ImageUrl}" Height="74" Stretch="Fill" Width="75"/>                                                                                       
                            <TextBlock TextWrapping="WrapWithOverflow" Background="LightGreen" FontSize="10" Name="txtblkImg"  HorizontalAlignment="Center" VerticalAlignment="Center" Height="74" Width="75">
                        <TextBlock  Text="{Binding Title}"/><LineBreak/><LineBreak/>
                        <TextBlock Text="by "/>
                        <TextBlock  Text="{Binding Author1}"/>
                       </TextBlock>                                                          
                    </Grid>                       
                </ControlTemplate>                   
            </Setter.Value>
        </Setter>
    </Style>

You should use a DataTrigger for this. Try this:

<ControlTemplate ... >
    <ControlTemplate.Triggers>
        <DataTrigger Binding="{Binding ImageUrl}" Value="{x:Null}">
            <Setter TargetName="txtblkImg" Property="Visibility" Value="Collapsed"/>
        </DataTrigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

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