我有以下代码:
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();
}
我想将SetBinding
方法的目标属性设置为TextBlock.TextProperty
,但每当我写TextBlock
时,我都会收到错误消息
在声明之前不能使用局部变量'TextBlock'。
答案 0 :(得分:0)
我怀疑这个代码存在问题 -
var TextBlock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (TextBlock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}
您已将变量名称声明为“TextBlock”。您尝试在绑定中设置的TextBlock.Text
属性与您在其下面声明的此变量名称相混淆。如果重命名此变量,问题可能会得到解决。
var textblock = win.sp_s.Children.OfType<TextBlock>().FirstOrDefault();
if (textblock.Visibility == System.Windows.Visibility.Visible)
{
sampleText.Visibility = System.Windows.Visibility.Visible;
}