0
首先,這只是用於測試目的動態添加文本框和更新綁定正好
我有一個只包含一個按鈕和2個stackpanels 的想法是有一個類,這個類將有碼的XAML頁面和與之相關的名字。代碼將被查詢,並根據結果顯示適當數量的文本框。我需要能夠在文本框的末尾添加名稱並保存列表。
這裏是我當前的代碼,它創建的文本框的方式我想它,但在列表的保存也不太清楚一旦被填入
XAML
<StackPanel x:Name="StackSG" Grid.Row="1" Grid.Column="0">
<ListBox ItemsSource="{Binding StackSG}" />
</StackPanel>
<StackPanel x:Name="StackSGName" Grid.Row="1" Grid.Column="1">
<ListBox ItemsSource="{Binding StackSGName}" />
</StackPanel>
<Button x:Name="Generate" Content="Generate" Height="23" Width="75" Grid.Row="0" Grid.Column="0"
Command="{Binding Path=GenerateSGKeys}"/>
</Grid>
</UserControl>
它連接到我的視圖odel看起來像這樣
public class stackpnl : Notify
{
private IEnumerable stackSG;
public IEnumerable StackSG
{
get { return stackSG; }
set { stackSG = value; OnNotifyPropertyChanged("StackSG"); }
}
private IEnumerable stackSGName;
public IEnumerable StackSGName
{
get { return stackSGName; }
set { stackSGName = value; OnNotifyPropertyChanged("StackSGName"); }
}
private DelegateCommand generateSGKeys;
public ICommand GenerateSGKeys
{
get { return generateSGKeys; }
}
private IEnumerable allotments;
public IEnumerable Allotments
{
get { return allotments; }
set { allotments = value; OnNotifyPropertyChanged("Allotments"); }
}
TextBox txtSGName = new TextBox();
public stackpnl()
{
generateSGKeys = new DelegateCommand(Generate, OnGenerate);
StackSG = new List<TextBox>();
StackSGName = new List<TextBox>();
}
private bool OnGenerate(object obj)
{
return true;
}
public class Allotment
{
#region Properties
public string AllotmentName { get; set; }
public string AllotmentCode { get; set; }
#endregion
}
private void Generate(object obj)
{
IList<TextBox> StackSGTmp = new List<TextBox>();
IList<TextBox> StackSGNameTmp = new List<TextBox>();
IList<Allotment> newList = new List<Allotment>();
int st = 10;
for (int i = 0; i < st; i++)
{
newList.Add(new Allotment() { AllotmentCode = string.Format("{0}{1}", "Code", i.ToString()), AllotmentName = string.Format("{0}{1}", "Code", i.ToString()) });
}
foreach (var Allotment in newList)
{
TextBox txtSG = new TextBox();
txtSG.Name = string.Format(Allotment.AllotmentCode);
txtSG.Height = 25;
txtSG.Width = 75;
txtSG.Text = string.Format(Allotment.AllotmentCode);
txtSG.Visibility = System.Windows.Visibility.Visible;
StackSGTmp.Add(txtSG);
//Add SG name textboxes
txtSGName = new TextBox();
txtSGName.Name = string.Format(string.Format("{0}{1}", Allotment.AllotmentCode, Allotment.AllotmentName));
txtSGName.Height = 25;
txtSGName.Width = 75;
txtSGName.SetBinding(TextBox.TextProperty, new Binding(Allotment.AllotmentName) { Mode = BindingMode.TwoWay });
txtSGName.Visibility = System.Windows.Visibility.Visible;
txtSGName.KeyDown += new KeyEventHandler(txtSGName_KeyDown);
StackSGNameTmp.Add(txtSGName);
}
StackSG = StackSGTmp;
StackSGName = StackSGNameTmp;
}
void txtSGName_KeyDown(object sender, KeyEventArgs e)
{
BindingExpression binding = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
}
謝謝!將更新我的代碼以反映這一點。 – Sl1ver