简体   繁体   中英

How to get TextBlock's Text value out of a StackPanel inside a Button in WPF

I want to know how to get the text value out of a TextBlock that's inside a StackPanel that's inside a button in WPF, it goes pretty much like this:

public MainWindow()
{
    Image img = new Image();
    img.Source = new BitmapImage(new Uri("image.png"));

    StackPanel stackPnl = new StackPanel();
    stackPnl.Orientation = Orientation.Vertical;
    stackPnl.Margin = new Thickness(10);
    stackPnl.Children.Add(img);

    TextBlock txtBlck = new TextBlock();
    txtBlck.Text = "this is a test!";
    stackPnl.Children.Add(txtBlck);

    Button btn = new Button();
    btn.Content = stackPnl;
    btn.Click += test_click;
    myPanel.Children.Add(btn);
}

And test_click:

private void test_click(object sender, RoutedEventArgs e)
{
    txtBox.Text = (sender as Button).Content.ToString();
}

Now of course what I get after I click on the button is this System.Windows.Controls.StackPanel , which I guess it's pretty obvious since the StackPanel is the actual content of the button, but like I said, I need to know how to get only the Text value of the TextBlock, so in that case txtBox should display this is a test! . How can this be done?, and thanks in advance!

From top of my head: 1. Store instance of TextBlock locally and use it when needed 2. Create DependencyProperty and bind it to TextBlock. It that case you will always have latest value in this DP.

Hope that helps.

Easiest way will be

TextBlock txtBlck = new TextBlock();
txtBlck.Name = "SomeName";
txtBlck.Text = "this is a test!";

and than

private void test_click(object sender, RoutedEventArgs e)
{
    txtBox.Text = SomeName.Text;
}

The button Content is your stackpanel not your textblock, then to have the textblock content you need to replace:

txtBox.Text = (sender as Button).Content;

by this

txtBox.Text = txtBlck.Text;

if u seriusly want text from textblock then y dont u make textblock public and use it.

public TextBlock txtBlck = new TextBlock();
        public MainWindow()
        {
            InitializeComponent();


            StackPanel stackPnl = new StackPanel();
            stackPnl.Orientation = Orientation.Vertical;
            stackPnl.Margin = new Thickness(10);


            txtBlck.Text = "this is a test!";
            stackPnl.Children.Add(txtBlck);

            Button btn = new Button();
            btn.Content = stackPnl;
            btn.Click +=btn_Click;
            myPanel.Children.Add(btn);
        }

        void btn_Click(object sender, RoutedEventArgs e)
        {
            txtBox.Text = txtBlck.Text;
        }

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