【问题标题】:WPF hyperlink in datatemplate listboxitem数据模板列表框项中的 WPF 超链接
【发布时间】: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


【解决方案1】:

您可以通过两种方式实现这一目标:

  1. 在您的父视图模型中创建一个ResultsViewModel 类型的属性(包含您的ResultsViewModel 对象集合)并将其绑定到您的ListBoxSelectedItem 属性。将某种RelayCommand 添加到父视图模型以处理删除操作,将Button 添加到您的DataTemplate 并将其Command 属性绑定到新命令。然后,当单击任何删除按钮时,您只需从集合中删除在 SelectedItem 属性中找到的项目,并且 UI 应相应更新(假设您已实现 INotifyPropertyChange 接口)。

  2. 您可以简单地从ListBox 中每个项目的DataTemplate 直接绑定到父视图模型。这假设您的父视图模型中有一个名为 DeleteCommand,并且父视图模型绑定到 WindowUserControlDataContext 属性,ListBox 出现在其中。还有请注意重要的CommandParameter="{Binding}" 部分,它在调用Command 时将集合中每个项目的数据对象传递给Command 中的object 参数。

例子:

<Button Content="X" Command="{Binding DataContext.Delete, 
    RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type 
    XmlNameSpace:WindowOrUserControlName}}, Mode=OneWay}" 
    CommandParameter="{Binding}" />

【讨论】:

    猜你喜欢
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多