• 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小示例下载:http://files.cnblogs.com/BABLOVE/WPF%E5%90%8E%E5%8F%B0%E8%AE%BF%E9%97%AEXAML%E5%85%83%E7%B4%A0.rar

  • 相关阅读:
    XML to Excel
    C# 位域[flags]
    使用windows7的System帐户
    VS.NET 控件命名规范
    Microsoft Robotics Studio到底能做什么?
    SQLServer系统表及其应用(转)
    利用xslt、xml,ajax实现了一个无限级树型导航
    利用xslt实现一个树形导航
    网页信息抓取如何获取延迟加载的网页数据
    站长盈利盈利方式面面观
  • 原文地址:https://www.cnblogs.com/BABLOVE/p/3232243.html
Copyright © 2020-2023  润新知