开发者

Get control in code from ControlTemplate By Name

I have next control template in my WPF app.

    <Style TargetType="Label" x:Key="LabelStyle">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Label">
                    <Grid>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="40"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <TextBox x:Name="MyTextBlock" Text="{TemplateBinding Content}"  Height="20" HorizontalAlignment="Left"  VerticalAlignment="Top" />
                        <Label Content="{TemplateBinding Content}" Grid.Column="1" Grid.Row="1"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

TextBox "MyTextBlock" is invisible in C# code of window. How can I access to this 开发者_Python百科textblock in code


Try binding your property to the textbox's visibility directly

<TextBox Visibility="{Binding IsFieldCodesEnabled, Converter={StaticResource BoolToVis}}" />

where BoolToVis is defined as:

<Resouces> 
    <loc:BooleanToVisibilityConverter k:key="BoolToVis"/> 
</Resources>


You can do a similar thing that XAML pages do in the code behind (except for you need to do it in OnApplyTemplate override):

public override void OnApplyTemplate() {
    base.OnApplyTemplate();

    var MyTextBlock = this.GetTemplateChild("MyTextBlock")
}

EDIT Just noticed that MyTextblock is actually a TextBox, so casting a TextBox to TextBlock will cause an exception. Try the updated code.


I found some solution for my situation. I just use loaded event of TextBox in my ControlTemplate

    private void MyTextBlock_Loaded(object sender, RoutedEventArgs e)
    {
        TextBox txt = sender as TextBox;
        if (txt!=null)
         {
            Messagebox.Show("It works");
         }

    }

But it is not so beautiful solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜