简体   繁体   中英

How to bind to a SelectedValue data context property in WPF?

I have a listbox that display some model items. I would like to hide some control below the listbox based on the boolean value of the model item associated with the selected listbox item.

I tried the following but it did not work:

1) set the ListBox SelectedValuePath="MyModelBooleanProperty"

2) add a data trigger to the control that I want to hide as follows

<DataTrigger Binding="{Binding ElementName=FolderList, Path=SelectedValue}" Value="False">
   <Setter Property="Visibility" Value="Collapsed"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=FolderList, Path=SelectedValue}" Value="True">
   <Setter Property="Visibility" Value="Visible"></Setter>
</DataTrigger>

I used this and it worked. Also make sure you don't explicitly set Visibility of TextBlock that overrides whatever the Style does.

<ListBox
     x:Name="FolderList"
     ItemsSource="{Binding Source={StaticResource ViewModel}, Path=List}"
     SelectedValuePath="SomeBooleanProperty">
     <ListBox.ItemTemplate>
         <DataTemplate>
             <TextBlock Text="{Binding SomeStringProperty}" />
         </DataTemplate>
     </ListBox.ItemTemplate>
 </ListBox>

 <TextBlock>
     <TextBlock.Style>
         <Style TargetType="TextBlock">
             <Setter Property="Visibility" Value="Visible" />
             <Style.Triggers>
                 <DataTrigger Binding="{Binding ElementName=FolderList, Path=SelectedValue}" Value="False">
                     <Setter Property="Visibility" Value="Collapsed" />
                 </DataTrigger>
                 <DataTrigger Binding="{Binding ElementName=FolderList, Path=SelectedValue}" Value="True">
                     <Setter Property="Visibility" Value="Visible" />
                 </DataTrigger>
             </Style.Triggers>
         </Style>
     </TextBlock.Style>
     My Text Block
 </TextBlock>

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