【发布时间】:2013-07-22 18:57:32
【问题描述】:
我在 WPF 中有一个数据模板,它附加到 ResultsViewModel 类并以表格格式呈现 VM。其中的一堆组成了 ListBox 中的 ListBoxItems。我想要的是在每个单独的表格中在边框的右上角有一个小 X,如果您单击它,它会调用一个从列表框中删除该项目的函数。
我已尝试使用超链接和事件 OnClick,但随后我必须在主 XAML 中而不是在资源字典中拥有 DataTemplate,因为它需要 x:Class 标记才能使用事件,但随后事件在 MainViewModel 中被触发,这不是世界上最糟糕的事情,因为可观察列表保存在 MainViewModel 中,无论如何都需要在那时删除,但我不知道如何获取对列表框项的 ResultsViewModel 的引用包含被点击的数据模板
<DataTemplate x:Key="ErroredResultsTemplate" DataType="x:Type vm:ResultsViewModel" >
<Border x:Name="Border" BorderBrush="{StaticResource ResultProcessedBorder}" Background="{StaticResource ResultFill}" BorderThickness="4" CornerRadius="10" Margin="6" Padding="5" Width="110" Height="110">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="83" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Foreground="{StaticResource ResultGrayText}" FontWeight="Bold" HorizontalAlignment="Right" VerticalAlignment="Top">
<Hyperlink Click="Close_Results">X</Hyperlink>
</TextBlock>
<TextBlock Width="90" Text="An error occurred calculating results" TextWrapping="Wrap" Foreground="{StaticResource ResultGrayText}" FontWeight="Bold" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Top" TextAlignment="Center" />
</Grid>
</Border>
</DataTemplate>
【问题讨论】:
-
而不是带有事件处理程序的超链接,您为什么不使用带有命令的
Button并让此命令驻留在您想要的任何位置(如果您想访问 ListBox,请使用 RelativeSource FindAncestor ListBox 的 DataContext 中的命令)并将命令的CommandParameter设置为{Binding Path=DataContext, RelativeSource={RelativeSource Self}}
标签: wpf datatemplate