我必须从ListView.ItemTemplate中的代码绑定到局部变量。我尝试过使用datacontext:
<ListView Name="listView" ItemsSource="{Binding}" DataContext="{Binding}" VerticalAlignment="Stretch" MaxHeight="300" Background="White" Foreground="Black" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" BorderBrush="#FFCDCDCD" BorderThickness="1" ScrollViewer.VerticalScrollBarVisibility="Auto" IncrementalLoadingTrigger="None" SelectionChanged="listView_SelectionChanged" >
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" MaxHeight="25" >
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Text}" Width="{Binding Width}" />
<Image Grid.Row="0" Grid.Column="1" Source="{Binding Image}" Stretch="None" Width="40" HorizontalAlignment="Left" Margin="4,0,0,0" />
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
代替“Width =”{Binding Width}“”我希望从datacontext获得属性 - 其余数据与itemsSource连接。如何“告诉”xaml使用datacontext中的属性? (现在它返回错误“未找到属性”)。我不想更改我的itemsource并添加宽度,因为它对于每个元素都是常量(很明显;))。
提前谢谢你:)
答案 0 :(得分:3)
使用DataContext
,ItemTemplate
是项目。您可以在树上向上找到另一个DataContext
,在这种情况下,您需要ListView's
:
{Binding DataContext.Width,
RelativeSource={RelativeSource AncestorType=ListView}}