C#WPF将DataGrid绑定到TabControl

时间:2014-06-21 14:28:53

标签: wpf xaml binding datagrid tabcontrol

我是WPF中的新手并且遇到数据绑定问题。我希望你能帮助我:

这是我的XAML代码:

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TabControl Name="MainTabControl" ItemsSource="{Binding}" Margin="2,0,-2,0">
            <TabControl.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding Header}" Tag="{Binding Rid}" />
                    </StackPanel>
                </DataTemplate>
            </TabControl.ItemTemplate>
            <TabControl.ContentTemplate>
                <DataTemplate>
                        <DataGrid ItemsSource="{Binding Dg}"   />
                </DataTemplate>
            </TabControl.ContentTemplate>
        </TabControl>

    </Grid>
</Window>

所以我有一个TabControl,它绑定了一个ObservableCollection选项卡。每个选项卡都有一个TextBlock作为Header和一个DataGrid。

结合:

 public MainWindow()
        {
            InitializeComponent();

            DataGrid dg = new DataGrid();
            DataGridTemplateColumn xx = new DataGridTemplateColumn()
            {
                Header = new TextBlock() { Text = "Edit", Tag = "Edit" }
            };
            xx.Width = new DataGridLength(1, DataGridLengthUnitType.Auto);
            dg.Columns.Add(xx);




            OCTabs.Add(new OCTab() { Header = "test1", Rid = 1 , Dg = dg});
            OCTabs.Add(new OCTab() { Header = "test2", Rid = 2 , Dg = dg});
            OCTabs.Add(new OCTab() { Header = "test3", Rid = 3, Dg = dg });
            MainTabControl.DataContext = OCTabs;



        }

这里是Tab-Class:

public class OCTab : INotifyPropertyChanged
    {
        private string _header;
        private int _rid;

        private DataGrid dg;

        public DataGrid Dg { get { return dg; } set { dg = value; NotifyPropertyChanged("Dg"); } }

        public string Header { get { return _header; } set { _header = value; NotifyPropertyChanged("Header"); } }
        public int Rid { get { return _rid; } set { _rid = value; NotifyPropertyChanged("Rid"); } }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

现在我的问题: 一切正常,除了每个Tab的DataGrids。 DataGrid为空(没有列,...) 绑定不起作用,我不知道为什么......

修改 那么每个Tabitem都有自己的数据网格吗?

0 个答案:

没有答案