简体   繁体   中英

Access to embedded WPF controls in xaml

Lets say I got the following user control:

<UserControl x:Class="MyUserControl">
    <tk:DataGrid>
        <tk:DataGrid.Columns>
            <!-- some columns -->
        </tk:DataGrid.Columns>
    </tk:DataGrid>
</UserControl>

Actually, I can't define what columns the data grid should have, since I need to use this control in many places, with different columns. Here is what I want to do:

<UserControl x:Class="MyPanel">
    <ui:MyUserControl>
        <Columns>
            <!-- columns that will go into the data grid -->
        </Columns>
    </ui:MyUserControl>
</UserControl>

Is it possible to achieve this?

PS: DataGrid.Columns is readonly, it is not possible to bind it to something else.

You can expose a depenency property on the UserControl called Columns which can bind to an internal DataGrid . You would access the property via <ui:MyUserControl.Columns> of course.

As @HB said in his solution, you should expose your own dependency property, but just performing binding wouldn't work, since the Columns property is read-only.

What you need to do is handle this in your dependency property's OnChange callback and add/remove columns as necessary. You'll also need to register to your dependency property's CollectionChanged event and possibly the grid's Columns CollectionChanged as well to synchronize the two properties.

Unfortunately, I don't think there's a XAML-only solution for this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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