简体   繁体   中英

How to get the Text from TextBlock inside a DataTemplate in code-behind

I have an Accordion Control where I bind values and display them in a DataTemplate. This is what I have in my user control :

<layoutToolkit:Accordion x:Name="MyAccordion">
<layoutToolkit:Accordion.ItemTemplate>
    <DataTemplate >
        <TextBlock x:Name="Header" Text="{Binding Header}"/>
    </DataTemplate>
</layoutToolkit:Accordion.ItemTemplate>
<layoutToolkit:Accordion.ContentTemplate>
    <DataTemplate>
        <StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock x:Name="Content" Text="{Binding Content}" />
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <Button x:Name="MyMethod" Content="Method" Click="MyMethod"/>
            </StackPanel>
        <StackPanel>
    </DataTemplate>
</layoutToolkit:Accordion.ContentTemplate>

My binding is working, now i want to be able to use the Text from the textblock to apply in a method in code behind, but I want the value to be different depending on which Accordion is open. Is it possible to achieve that ?

This is how my code-behind is :

        public MyUserCOntrol()
    {
        InitializeComponent();
        this.MyAccordion.SelectionMode = AccordionSelectionMode.ZeroOrOne;

        //method to fill the accordion
        this.MyAccordion.ItemsSource = MainWindow._RE.ListActionsParType;
    }

    public void MyMethod(object sender, EventArgs e)
    {
        string TxtBlockContent = ....;
        // so i can use this value in other operations
    }

I want to create a method (here it's myMethode) that I will apply on a button click and that use this value depending on which accordion is open

If you need to get the text of the TextBlock you displayed in the DataTemplate, then you can achieve it by using the below way,

//In the textblock you used in XAML

<TextBlock Loaded="Txt_Loaded">

//In code-behind

private void Txt_Loaded(object sender, RoutedEventArgs e)
{
    var myText = (sender as TextBlock).Text;
}

The above event will be fired whenever the TextBlock is loaded into view. So, you can get the text in the TextBlock as like in the above code.

使用“ BindingContextChanged”事件获取发件人(实际视图,TextBlock)。

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