简体   繁体   中英

DataTrigger RelativeSource WPF XAML

The thing I want to make When mouseover in grid Border Visibilty property value must change.

I have a grid with a 3 ColumnDefinition.

在此处输入图片说明

The code is

<Grid x:Name="grid1">
     <Grid.ColumnDefinitions>
          <ColumnDefinition Width="5*"/>
           <ColumnDefinition Width="27*"/>
           <ColumnDefinition Width="93*"/>
      </Grid.ColumnDefinitions>
      <Border Grid.Column="0" Background="Blue" Visibility="Hidden">
           <Border.Style>
                <Style>
                   <Style.Triggers>
                    <DataTrigger Binding="{Binding IsMouseOver , RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" Value="True">
                     <Setter Property="Border.Visibility" Value="Visible" />
                     </DataTrigger>
                     </Style.Triggers>
                   </Style>
               </Border.Style>
          </Border>
        <Image  Grid.Column="1" />
         <TextBlock Grid.Column="2" />

   </Grid>

When mouseover the grid nothing is happen.so This codes not working

one thing is that you should not use IsReadOnly property in DataTrigger when MouseOver is required.

another one is that local value Visibility="Hidden" has higher priority than DataTrigger setter <Setter Property="Border.Visibility" Value="Visible" /> and will not be changed even if condition is true

a fix for both (initial value of Visibility is defined in a setter)

<Border Grid.Column="0" Background="Blue">
    <Border.Style>
        <Style>
            <Setter Property="Border.Visibility" Value="Hidden" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding IsMouseOver, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}}" Value="False">
                    <Setter Property="Border.Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
</Border>

you should also set Grid Background to non-null value (eg <Grid x:Name="grid1" Background="Transparent"> ) for mouse movements to be registered in grid ( {x:Null} vs. Transparent? )

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