2016-05-03 169 views
1

我想在每個選項卡中動態地創建多個TabItem有一個文本框。然後我想將每個文本框綁定到字典索引。例如將文本框綁定到字典

TAB1 | TAB2 | TAB3

TextBox1 | TextBox2 | TextBox3

詞典[TAB1]結合TextBox1的...等

我這樣做:

Dictionary<string, string> dic = new Dictionary<string, string>(); 

      Binding binding = new Binding(); 
      binding.Source = dic[id]; 
      binding.Path = ??? 

      TextBox stb = new TextBox() 
      { 
       Name = "tb" + id 

      }; 
      stb.SetBinding(TextBox.Text, binding); 

我應該把什麼路徑?

回答

2

您可以使用視圖模型動態創建此模型: 1.創建一個主視圖模型來保存選項卡。

public class MainViewModel 
{ 
    private ObservableCollection<TabViewModel> tabs = new ObservableCollection<TabViewModel>(); 


    public ObservableCollection<TabViewModel> Tabs 
    { 
     get { return this.tabs; } 
    } 
} 
  • 創建TabViewModel,將持有字典和標題顯示。在這個例子中,標題是字典的關鍵,但你可以增強它。

    公共類TabViewModel 私有隻讀字典字典;

    public TabViewModel(Dictionary<string, string> dictionary) 
        { 
         this.dictionary = dictionary; 
        } 
    
        public string Header { get; set; } 
        public string TextValue { 
         get { return this.dictionary[Header]; } 
         set { this.dictionary[Header] = value; }} 
    } 
    
  • 創建的TabControl的ItemsSource使用:

    <TabControl VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ItemsSource="{Binding Path=Tabs}" > 
         </TabControl> 
    
  • 風格分配給它

  • <Style TargetType="TabItem"> 
     
            <Setter Property="Header" Value="{Binding Path=Header}"/> 
     
            <Setter Property="ContentTemplate"> 
     
             <Setter.Value> 
     
              <DataTemplate DataType="sOfExamples:TabViewModel"> 
     
              <TextBox Text="{Binding Path=TextValue}"></TextBox> 
     
              </DataTemplate> 
     
             </Setter.Value> 
     
            </Setter> 
     
           </Style>

  • 分配數據上下文:

    MainViewModel mainViewModel = new MainViewModel(); 詞典=新詞典(); dictionary.Add(「Header1」,「Header 1 text」); dictionary.Add(「Header2」,「Header 2 text」);

     mainViewModel.Tabs.Add(new TabViewModel(dictionary) 
         { 
          Header = "Header1" 
         }); 
         mainViewModel.Tabs.Add(new TabViewModel(dictionary) 
         { 
          Header = "Header2" 
         }); 
    
         this.DataContext = mainViewModel; 
    
  • 你可以,如果你想雙向綁定更新上tabviewmodel執行INotifyPropertyChanged。

    +0

    非常感謝您的解釋。我會嘗試並提供反饋 –

    1

    幾件事情需要注意:

    1. 爲了能夠綁定到它,詞典必須是公共財產:

      public Dictionary<string, string> dic { get; set; } = new Dictionary<string, string>(); 
      
    2. 申請綁定到文本框'Text屬性,您需要引用依賴屬性本身而不是其值:

      stb.SetBinding(TextBox.TextProperty, binding); 
      
    3. 最後,你正在混合綁定的SourcePath屬性:binding.Path是實際綁定目標所屬的地方,而Source引用持有此目標的對象,在這種情況下,這是當前類(或者可以設置在Avneesh的答案描述

      binding.Source = this; 
      binding.Path = new PropertyPath("dic[" + id "]"); 
      

    然而,更優雅的解決方案是結合整個標籤的項目:文本框」 DataContext屬性,然後將其自動應用的結合來源所有綁定) 。