从DataTemplate中的TextBlock获取文本

时间:2017-04-14 09:54:31

标签: c# wpf

当TextBlock在DataTemplate中时,如何从TextBlock中获取Text后面的代码?我知道正确的方法是制作{Binding},但在我的情况下我没有约束力。

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate x:Key="ToggleDataTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock x:Name="PART_ToggleButtonContent" Text="Pause" VerticalAlignment="Center"/>
            </StackPanel>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding ElementName=PART_ToggleButtonContent,Path=IsChecked}" Value="True">
                    <Setter TargetName="PART_ToggleButtonContent" Property="Text" Value="Resume" />
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ToggleButton x:Name="Test" Width="80" Height="40" ContentTemplate="{StaticResource ToggleDataTemplate}" />
    </Grid>
</Window>

代码:

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            //How to get text from Template?
        }
    }
}

0 个答案:

没有答案