[英]How to create databinding in code behind using the same object that is initiated in xaml?
[英]How to create databinding in code behind for a textblock that is created also in code behind?
我有以下代碼:
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
方法的target屬性設置為TextBlock.TextProperty
但是每當我編寫TextBlock
,都會出現錯誤提示
聲明之前不能使用局部變量'TextBlock'。
我懷疑問題出在此代碼-
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.