wpf 如何从列表视图数据模板中获取对象?

knpiaxh1  于 2023-04-22  发布在  其他
关注(0)|答案(1)|浏览(139)

我有一个列表视图,我使用的gridview有3列。第一列显示一个名为CanvasView的对象的名称,我将其作为列表视图的ItemsSource。接下来的两个gridview列是按钮,需要来自该列表的CanvasView对象,即ItemsSource。我如何才能获得它?
ItemsSource的XAML:

<ListView x:Name="ViewsList" ItemsSource="{Binding Path=CanvasViews, Mode=TwoWay}" 
          SelectionChanged="ViewsList_SelectionChanged" Loaded="ViewsList_Loaded" >
    <ListView.View>
        <GridView>

            <GridViewColumn Header="Name">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox x:Name="ViewNameTextBox" Height="20" Width="60" Grid.Column="0"
                                VerticalContentAlignment="Center" Text="{Binding Path=ViewName, UpdateSourceTrigger=PropertyChanged}" 
                                IsReadOnly="{Binding Path=IsReadOnly}" BorderBrush="{Binding Path=BorderColor}">
                        </TextBox>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>

            <GridViewColumn Header="Go">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Button x:Name="GoToView" Style="{StaticResource TinyRoundedButton}" Click="GoToView_Click"  />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>

            <GridViewColumn Header="Delete">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <Button x:Name="DeleteView" Style="{StaticResource TinyRoundedButton}" Foreground="#BFE83131" Click="DeleteView_Click" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>

        </GridView>
    </ListView.View>
</ListView>

下面是我需要对象的click事件:

private void GoToView_Click(object sender, RoutedEventArgs e)
        {
            
        }

我需要获取与按钮在同一行的对象。我如何才能做到这一点?

ppcbkaq5

ppcbkaq51#

ButtonDataContext继承自DataTemplate(因为您没有显式地分配它)。DataTemplateDataContext始终是应用模板的实际行/项的数据项。

private void GoToView_Click(object sender, RoutedEventArgs e)
{
  var button = sender as Button;
  var canvasViewItem = button.DataContext as CanvasView;
}

相关问题