WPF后台访问XAML元素

当我们需要从后台访问xaml文件时,我们可以通过这样的方式来操作:

  private void button1_Click(object sender, RoutedEventArgs e)
        {
            
            System.Windows.MessageBox.Show(this.textBox1.GetValue(TextBox.TextProperty).ToString());
        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
             TextBox t = this.FindName("textBox1") as TextBox;
           
            System.Windows.MessageBox.Show("第二种方式:" + t.Text);
        }

        private void button3_Click(object sender, RoutedEventArgs e)
        {
            var v = this.Content;
            Grid g = v as Grid;
            UIElementCollection uc = g.Children;

            Control[] us = new Control[uc.Count];
            g.Children.CopyTo(us, 0);
            string str = (us.First(a => a.Name == "textBox1") as TextBox).Text;
            System.Windows.MessageBox.Show("第三种方式:" + str);
        }

xaml文件:

<Window x:Class="WPF后台访问XAML元素.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Background="BlanchedAlmond">
        <TextBox Height="35" HorizontalAlignment="Left" FontSize="24" Margin="98,29,0,0" Name="textBox1" VerticalAlignment="Top" Width="237" >HELLO WORD!</TextBox>
        <Button Content="方式一" Height="30" HorizontalAlignment="Left" Margin="107,109,0,0" Name="button1" VerticalAlignment="Top" Width="220" Click="button1_Click" />
        <Button Content="方式二" Height="30" HorizontalAlignment="Left" Margin="107,146,0,0" Name="button2" VerticalAlignment="Top" Width="220" Click="button2_Click" />
        <Button Content="方式三" Height="30" HorizontalAlignment="Left" Margin="107,182,0,0" Name="button3" VerticalAlignment="Top" Width="220" Click="button3_Click" />
    </Grid>
</Window>

具体效果演示:

demo小示例下载:https://files.cnblogs.com/BABLOVE/WPF%E5%90%8E%E5%8F%B0%E8%AE%BF%E9%97%AEXAML%E5%85%83%E7%B4%A0.rar

posted @ 2013-08-02 11:43  如梦不是梦  阅读(1299)  评论(0编辑  收藏  举报