Search code examples
wpfvb.netbindingitemssource

Access to a property called inside an ItemTemplate outside its binding


Having this Properties and an ItemsControl binding to one of them:

Public Property Description As String
    Get
        Return _description
    End Get
    Set(value As String)
        _description = value
    End Set
End Property

Public Property Options As List(Of ItemOption)
    Get
        Return _options
    End Get
    Set(value As List(Of ItemOption))
        _options = value
    End Set
End Property

<ItemsControl ItemsSource="{Binding Path=Options}" ItemTemplate="{DynamicResource OptionsTemplate}"/>

In the ItemTemplate I have access to the properties of the property called Options, of course. But it is possible to have access to the property called Description inside this ItemTemplate?


Solution

  • You could use RelativeSource.

    For example this is how could be your OptionTemplate:

    <UserControl x:Class="OptionTemplate"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:local="clr-namespace:OptionTemplate"
                 xmlns:i="clr-namespace:System.Windows.Interactivity;ssembly=System.Windows.Interactivity"
                 xmlns:prism1="http://prismlibrary.com/"
                 mc:Ignorable="d" >
    
       <Grid>
           <TextBlock Text="{Binding DataContext.Description, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ItemsControl}}" />
           <!-- Your others controls -->
       </Grid>
    
    </UserControl>