简体   繁体   中英

ItemsControl DataContext Binding Error

I have already looked into this solution: Show if ItemsControl.ItemsSource is null . I set the DataContext of the ItemsControl via codebehind to an ObservableCollection. Everything works fine except that it only resolves once during the loading phase. If the items control has a few items in the start, the text disappears but doesn't appear later onwards. If it's empty, the text appears, but it doens't go away when i add items later on. I have tried ItemsSource as well but no luck. I'm aware im using a control template as of now, and i can use relative source TemplatedParent but i just wanted to make sure. Upon further testing, the converter function doesn't seem to activate after i try to add/remove items in the list even though the items show on my itemscontrol.

<ItemsControl x:Name="MedicationList" ItemTemplate="{StaticResource UserTemplate}">
  <ItemsControl.Template>
    <ControlTemplate TargetType="ItemsControl">
      <Grid>
        <TextBlock Text="No Items to Display" Visibility="{Binding DataContext, ElementName=MedicationList, Converter={StaticResource AnyItemsToVisibilityConverter}}" />
        <ItemsPresenter />
      </Grid>
    </ControlTemplate>     
  </ItemsControl.Template>
</ItemsControl>

What are you using as the datacontext/itemssource? If it is an ObservableCollection as I would expect, then you would be best off binding to its "Count" property and then using a trigger to collapse the text block when necessary.

The reason that the binding isn't currently updating is that the DataContext itself isn't actually changing. Properties on the DataContext ARE changing, so if you bind to the correct property (count) your bindings will update.

This code snippet should work:

<ControlTemplate TargetType="ItemsControl">
  <Grid>
    <TextBlock x:Name="txtBlock" Text="No Items to Display" Visibility="Collapsed" />
    <ItemsPresenter />
  </Grid>
  <ControlTemplate.Triggers>
    <DataTrigger Binding="{Binding Path=Count}" Value="0">
      <Setter TargetName="txtBlock" Property="Visibility" Value="Visible"/>
    </DataTrigger>
  </ControlTemplate.Triggers>
</ControlTemplate>  

By using a data trigger you can avoid the need for a converter to convert a numeric value into a visibility and keep everything in your .xaml.

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