[英]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: 我想知道如何从WPF中按钮内的StackPanel内的TextBlock中获取文本值,它非常像这样:
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: 和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!
现在,当然,我单击按钮后得到的是这个
System.Windows.Controls.StackPanel
,由于StackPanel是按钮的实际内容,我想这很明显,但是就像我说的那样,我需要知道如何仅获取TextBlock的Text值,因此在这种情况下txtBox应该显示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. 从我的头开始:1.在本地存储TextBlock的实例,并在需要时使用它。2.创建DependencyProperty并将其绑定到TextBlock。 It that case you will always have latest value in this DP.
那样的话,您将在此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: 按钮Content是您的堆栈面板而不是您的文本块,然后要替换该文本块内容,您需要:
txtBox.Text = (sender as Button).Content; txtBox.Text =(发送为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. 如果您非常想从textblock中获取文本,则不要公开使用textblock。
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.