簡體   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?

我不明白為什么數據模板內的按鈕可以知道加載的事件在后面的代碼中,但不能簡單地將后面的代碼用作數據上下文。

我知道解決這個問題的解決方案,但我不確定為什么將命令綁定到數據模板中的按鈕並不容易。

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>

代碼背后

        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)
        {

        }

這基於使用 XAML 編譯器和 DataContext 工作的事件處理方式。 在按鈕上指定事件處理程序時,XAML 編譯器會生成如下內容:

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

按鈕本身實際上並不知道該事件,而是從 XAML 生成的代碼將事件掛鈎到相應的按鈕。

另一方面,DataContext 由系統以不同方式處理。 DataContext 是向下傳播的東西。 因此,您的按鈕 DataContext 是通過向上走可視化樹並找到為您提供 DataContext 的第一個元素來確定的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM