[英]How to create databinding in code behind for a textblock that is created also in code behind?
I have the following code : 我有以下代码:
private void Ok_Click(object sender, MouseButtonEventArgs e)
{
MainWindow win = (MainWindow)Application.Current.MainWindow;
int i = 1; // counter for the name of each new textblock
string name = String.Concat("sample", i);
// add textblok to the document list of new samples
if (File_name.Text != "")
{
TextBlock sampleText = new TextBlock();
sampleText.Text = File_name.Text;
sampleText.FontSize = 14;
sampleText.FontFamily = new FontFamily("Sans-serif");
sampleText.FontWeight = FontWeights.DemiBold;
sampleText.Margin = new Thickness(20,0,0,0);
sampleText.Name = name;
sampleText.PreviewMouseDown += new MouseButtonEventHandler(test1);
sampleText.Visibility = System.Windows.Visibility.Collapsed;
//binding
Binding myBinding = new Binding();
myBinding.Source = Application.Current;
myBinding.Path = new PropertyPath("sampleName");
myBinding.Mode = BindingMode.TwoWay;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
sampleText.SetBinding(, myBinding);
Grid.SetColumn(sampleText, 0);
win.sp_s.Children.Add(sampleText);
// checking if the drop down of sample is already open,
//if so it will show the last textblock with pressing the arrow button.
var TextBlock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (TextBlock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
}
i += 1; // increasing the loop of names by 1
this.Close();
}
I want to set the target property of the SetBinding
method to TextBlock.TextProperty
but whenever I write TextBlock
I get an error stating 我想将
SetBinding
方法的target属性设置为TextBlock.TextProperty
但是每当我编写TextBlock
,都会出现错误提示
Cannot use local variable 'TextBlock' before it is declared.
声明之前不能使用局部变量'TextBlock'。
I suspect the issue is with this code - 我怀疑问题出在此代码-
var TextBlock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (TextBlock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
You have declared a variable name as "TextBlock". 您已将变量名称声明为“ TextBlock”。 The
TextBlock.Text
property you are trying to set inside the binding is getting confused with this variable name you have declared below it. 您试图在绑定内设置的
TextBlock.Text
属性与您在其下方声明的变量名称相混淆。 If you rename this variable the issue might get fixed. 如果重命名此变量,则问题可能会得到解决。
var textblock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (textblock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.