简体   繁体   中英

How to access control inside of a ControlTemplate

How can I access my btnViewTable from code-behind? Specifically to be able to set the visibility on or off, or even remove it. I've looked at GetTemplateChild as well as FindName, but have been unable to access the button. I can manage to obtain a reference to the ControlTemplate, but can't get any further than that.

<Grid x:Name="pnlSearch" Background="White">
<TextBlock x:Name="txtSearchResults" />
<sdk:DataGrid x:Name="grdResults">
<sdk:DataGrid.Columns>
    <sdk:DataGridTextColumn Binding="{Binding Value}"/>
    <sdk:DataGridTextColumn Binding="{Binding FoundFieldName}"/>
</sdk:DataGrid.Columns>
<sdk:DataGrid.RowGroupHeaderStyles>
    <Style TargetType="sdk:DataGridRowGroupHeader">
    <Setter Property="Template">
        <Setter.Value>
        <ControlTemplate TargetType="sdk:DataGridRowGroupHeader">
            <sdk:DataGridFrozenGrid Name="Root">
            <StackPanel>
                <Button x:Name="btnViewTable"
var button = (Button)DataGrid.Template.FindName("btnViewTable", "DataGridControl");
button.Click += //Do something;

Where DataGrid/DataGridControl is the actual DataGridControl

To handle parts of the template, from outside of the control, is always a not-so-good idea.

For a quick fix, I'd go with:

<Style TargetType="sdk:DataGridRowGroupHeader">
    <Setter Property="Tag" Value="{Binding SomeVisibilityProperty}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="sdk:DataGridRowGroupHeader">
                <Grid
                    <sdk:DataGridFrozenGrid Name="Root">
                    <StackPanel>
                        <Button x:Name="btnViewTable"
                                Visibility="{TemplateBinding Tag}"

Where SomeVisibilityProperty is a property in the data context. Might need to use RelativeSource .

For a "true" fix, I'd define an attached property. Set this property to bind to the same property on parent grid and then have the button to bind to the property on DataGridRowGroupHeader .

I ended up just referring to a property in codebehind:

http://www.jayway.com/2011/05/17/bind-from-xaml-to-property-defined-in-code-behind/

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