简体   繁体   English

DataTemplate 中的按钮如何注册并监听后面代码中按钮的加载事件,但无法访问数据上下文?

[英]How can a button inside of a DataTemplate register and listen to a loaded event of the button in the code behind, but can't access the datacontext?

I don't understand why a button inside of a datatemplate can know the loaded event is in the code behind, but can't simply use the code behind as the data context.我不明白为什么数据模板内的按钮可以知道加载的事件在后面的代码中,但不能简单地将后面的代码用作数据上下文。

I know of solutions to solve this, but I'm not sure why it isn't easier to bind a command to a button within a datatemplate.我知道解决这个问题的解决方案,但我不确定为什么将命令绑定到数据模板中的按钮并不容易。

Xaml Xaml

<grid:RadDataGrid Margin="0" ItemsSource="{x:Bind _viewModel.Data, Mode=OneWay}" Width="600" HorizontalAlignment="Left">
            <grid:RadDataGrid.Columns>
                <grid:DataGridTemplateColumn Header="Delete" SizeMode="Fixed">
                    <grid:DataGridTemplateColumn.CellContentTemplate>
                        <DataTemplate>
                            <StackPanel x:Name="stackPanel" Style="{StaticResource ResourceKey=RadDataGridButtonPanel}">
                                <Button Command="{Binding _viewModel.DeleteCommand, ElementName=deleteView}" Loaded="DeleteButton_Loaded">
                                </Button>
                            </StackPanel>
                        </DataTemplate>
                    </grid:DataGridTemplateColumn.CellContentTemplate>
                </grid:DataGridTemplateColumn>
            </grid:RadDataGrid.Columns>
 </grid:RadDataGrid>

Code Behind代码背后

        private readonly ViewModel _viewModel;

        public DeleteView()
        {
            this.InitializeComponent();
            _viewModel = new ViewModel();
            this.DataContext = _viewModel;

        }

        private void DeleteButton_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {

        }

This is based on how events are being handled with the XAML compiler, and DataContext works.这基于使用 XAML 编译器和 DataContext 工作的事件处理方式。 When specifying an eventhandler on your button, the XAML Compiler generates something like this:在按钮上指定事件处理程序时,XAML 编译器会生成如下内容:

var button1 = Page.GetElement("buttonInTemplate") //Some magic to get the button
button1.Loaded += Page.DeleteButton_Loaded;

The button itsself isn't actually aware of the event, instead the code generated from XAML hooks the event to the appropriate button.按钮本身实际上并不知道该事件,而是从 XAML 生成的代码将事件挂钩到相应的按钮。

The DataContext on the other hand gets handled by the system differently.另一方面,DataContext 由系统以不同方式处理。 DataContext is something that propagates down. DataContext 是向下传播的东西。 So your buttons DataContext is determined by walking up the visual tree and finding the first element that provides you with the DataContext.因此,您的按钮 DataContext 是通过向上走可视化树并找到为您提供 DataContext 的第一个元素来确定的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM