1

我想使用标准的 ContentTemplate 将 TabItems 动态添加到 TabControl,该标准 ContentTemplate 由网格和一些其他输入控件(如文本框和按钮)组成。有人可以帮我实现这一目标吗?

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

4

1 回答 1

1

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

如果链接不起作用,这是这个类作为另一个问题的答案。

xml:

<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();
    }
}
于 2010-10-23T15:54:31.067 回答