2010-10-22 64 views
1

我想用标准ContentTemplate动态添加TabItems到TabControl,包括网格和几个其他输入控件,如文本框和按钮。有人可以帮我实现这个目标吗?另外,如果我尝试从WCF服务异步加载数据到网格,肯定会有时间滞后。那么即使选定的选项卡不同,我该如何将数据完全绑定到正确的网格? (这里的问题是我怎么找到合适的网格控件绑定)Silverlight:使用标准ContentTemplate为所有选项卡动态添加TabItems到TabControl

回答

1

使用此派生类MyTabControl:http://pastebin.mozilla.org/1040446

如果thelink不行,here is this class作为回答另一个问题。

的XAML:

<my:MyTabControl MyItemsSource="{Binding Pages}" MySelectedItem="{Binding CurrentPage, Mode=TwoWay}"> 
    <my:MyTabControl.TabItemTemplate> 
    <DataTemplate> 
     <Grid> 
      <Grid.ColumnDefinitions> 
      <ColumnDefinition Height="Auto" /> 
      <ColumnDefinition Height="Auto" /> 
      </Grid.ColumnDefinitions> 
      <TextBox Text="{Binding SomeText1, Mode=TwoWay}"/> 
      <Button Content="Button" Command="{Binding SomeCommand}" Grid.Column="1"/> 
     </Grid> 
    </DataTemplate> 
    </my:MyTabControl.TabItemTemplate> 
    <my:MyTabControl.TabHeaderItemTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding Title}" /> 
    </DataTemplate> 
    </my:MyTabControl.TabHeaderItemTemplate> 
</my:MyTabControl> 

视图模型:

public class TabItemModel : INotifyPropertyChanged 
{ 
    public string Title {get; set;} 
    private string someText1; 
    public string SomeText1 
    { 
     get { return someText1; } 
     set 
     { 
      someText1 = value; 
      OnPropertyChanged("SomeText1"); 
     } 
    } 
    public ICommand SomeCommand {get; set;} 
    //... 
} 

public class MainViewModel 
{ 
    public MainViewModel 
    { 
     this.Pages = new ObservableCollection<TabItemModel>(); 
     this.Pages.Add(new TabItemModel{Title="Title1", SomeText1="Text1"}); 
     this.Pages.Add(new TabItemModel{Title="Title2", SomeText1="Text2"}); 
    } 

    public ObservableCollection<TabItemModel> Pages {get; set;} 
    //selected tab is different 
    public TabItemModel CurrentPage {get; set;} 

    public void SomeDataFromService() 
    { 
     //bind the data to the right grid 
     var ti = this.Pages.FirstOrDefault(p => p.Title == "Title2"); 
     if(ti != null) 
      ti.SomeText1 = "Text from service"; 
    } 
} 

最后:

public partial class MainPage : UserControl 
{ 
    public MainPage() 
    { 
     InitializeComponent(); 
     this.DataContext = new MainViewModel(); 
    } 
}