2012-01-26 112 views
2

我無法將值綁定到動態創建的控件。當用戶加載一個自定義文件並且該文件將具有未知數量的參數。參數有一個Group屬性,在分組時會動態地將tabItems添加到tabControl。然後,我遍歷參數並添加一個標籤,並且現在將一個文本框添加到選項卡中的一個網格中。儘管我打算根據建築物類型使用不同的控件。我想將參數Value屬性綁定到文本框。標籤,標籤和文本框添加正常,但沒有任何值綁定綁定到動態創建的控件

他,如果我還沒有重新考慮解決方案到目前爲止;

myTab.Items.Clear(); 

    var args = viewModel.Arguments; 
    var groups = args.GroupBy(arg => arg.Groups); 

foreach (var group in groups) 
{ 
    TabItemExt tab = new TabItemExt(); 
    tab.Header = group.Key; 

    Grid grid = new Grid(); 

    grid.ColumnDefinitions.Add(new ColumnDefinition()); 
    grid.ColumnDefinitions.Add(new ColumnDefinition()); 

    int count = 0; 
    foreach (var argument in group) 
    { 
     RowDefinition newRow = new RowDefinition(); 
     grid.RowDefinitions.Insert(count, newRow); 

     LabelTextBlock label = new LabelTextBlock(); 
     label.Text = argument.DisplayName; 

     Grid.SetRow(label, count); 
     Grid.SetColumn(label, 0); 

     TextBox textBox = new TextBox(); 
     var binding = new Binding(); 
     binding.Source = viewModel.Arguments[argument.Name]; 
     //binding.Source = argument 
     binding.Path = new PropertyPath("Value"); 

     textBox.SetBinding(TextBlock.TextProperty, binding); 

     Grid.SetRow(textBox, count); 
     Grid.SetColumn(textBox, 1); 

     grid.Children.Add(label); 
     grid.Children.Add(textBox); 
     count += 1; 
    } 

    tab.Content = grid; 
    myTab.Items.Add(tab);  
} 
+0

我假設'viewModel.Arguments [argument.Name] .Value'是一個有效的屬性?爲什麼不使用類似'ItemsControl'的東西來從XAML生成控件而不是代碼隱藏? – Rachel

+0

viewModel.Arguments [argument.Name] .Value是一個有效的屬性yes。 – theHaggis

+0

視圖是否公開可用於查找何時嘗試綁定其數據? – Rachel

回答

1
textBox.SetBinding(TextBlock.TextProperty, binding); 

應該已經

textBox.SetBinding(TextBox.TextProperty, binding); 

只是略高於依賴於智能感知。