Silverlight:使用标准ContentTemplate为所有选项卡动态地将TabItems添加到TabControl

时间:2010-10-22 20:29:08

标签: .net silverlight tabcontrol tabitem

我想将TabItems动态添加到TabControl,标准的ContentTemplate包含一个网格和一些其他输入控件,如文本框和按钮。有人可以帮助我实现这个目标吗?

此外,如果我尝试将数据从WCF服务异步加载到网格,肯定会有时间延迟。那么,即使所选标签不同,如何将数据精确绑定到正确的网格呢? (这里的问题是如何找到要绑定的正确网格控件)

1 个答案:

答案 0 :(得分:1)

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

如果链接不起作用,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();
    }
}