访问在其绑定之外的 ItemTemplate 内部调用的 属性
Access to a property called inside an ItemTemplate outside its binding
将此属性和 ItemsControl 绑定到其中之一:
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}"/>
在 ItemTemplate 中,我当然可以访问名为 Options 的 属性 的属性。但是可以访问此 ItemTemplate 中名为 Description 的 属性?
您可以使用 RelativeSource。
例如,这就是您的 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>
将此属性和 ItemsControl 绑定到其中之一:
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}"/>
在 ItemTemplate 中,我当然可以访问名为 Options 的 属性 的属性。但是可以访问此 ItemTemplate 中名为 Description 的 属性?
您可以使用 RelativeSource。
例如,这就是您的 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>