代码之家  ›  专栏  ›  技术社区  ›  Geeth

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

  •  1
  • Geeth  · 技术社区  · 14 年前

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

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

    如何在代码中包含此选项。(如果图像源[ImgUrl]值为空,我想将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 回复  |  直到 8 年前
        1
  •  1
  •   CyberFox    9 年前

    你应该使用 DataTrigger 为了这个。试试这个:

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