سؤال

If I create a DataGrid in code behind with some arbitrary columns added to it I can not get the visual tree to be created for the DataGrid. I need to edit the CellStyle properties of particular rows dynamically, so I would like to be able to use the VisualTreeHelper function on my DataGrid objects at run time. How can I build the visual tree for DataGrid objects created dynamically? The tree is built with no problems if I use XAML to build one at design-time, but I am not sure how to do this for a dynamic case.

A trivial sample case for my problem is as such:

    <Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
        <Grid Name="MainGrid" />
    </Window>

With the code behind as:

    Class MainWindow
        Dim dg As DataGrid
        Dim col As DataGridTextColumn

        Sub New()
            InitializeComponent()

            col.Header = "HEAD0RR"
            dg.Columns.Add(col)
            MainGrid.Children.Add(dg)
        End Sub
    End Class

But the WPF Tree Visualizer just shows the DataGrid I created as having no parents or children, and the VisualTreeHelper function thus does not work.

هل كانت مفيدة؟

المحلول

The tree is built with no problems if I use XAML to build one at design-time, but I am not sure how to do this for a dynamic case.

First of all, "XAML" and "dynamic" are not mutually exclusive. Are you absolutely sure you need build the grid and access CellStyles through procedural (VB) code? There are multiple options from XAML that are easier, more maintainable, and more dynamic than explicitly scanning the visual tree. For example:

As for why you can't see items in the visual tree: When are you trying to access it? It won't populate instantly. You may need to wait for the Loaded event, or the StatusChanged event of the DataGrid's ItemContainerGenerator.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top