WPF - 控制模板和基于数据的控件可见性

时间:2010-10-14 04:59:37

标签: wpf listbox control-template

我正在使用Control模板来显示列表框项目。我想根据项目值设置控件的可见性。

我需要与How can I replace an image in a WPF grid with another control depending on the source data?

相同

如何在我的代码中包含此选项。 (如果图像源[ImgUrl]值为null,我想将textblock [txtblkImg]可见性设置为折叠。)

我的代码:

        <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>

1 个答案:

答案 0 :(得分:1)

您应该使用DataTrigger。试试这个:

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