如何使用ItemsControl分配<datagrid.columns>?</datagrid.columns>

时间:2012-04-17 08:53:13

标签: wpf mvvm mvvm-light wpfdatagrid

我在控件中有一个datagrid(这里是:DataGridSelectorControl),我想用ItemTemplate创建它的coulmns.actually我想做这样的事情:

  <DataGrid  x:Name="grd" ItemsSource="{Binding Source={StaticResource theSource}}" AutoGenerateColumns="False"  >
                <DataGrid.Columns>
                <ItemsControl ItemsSource="{Binding DataGridColumnItems}">
                    <ItemsControl.ItemsPanel>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal" />
                        </ItemsPanelTemplate>
                    </ItemsControl.ItemsPanel>
                </ItemsControl>
                </DataGrid.Columns>
            </DataGrid>

我想知道有没有办法使用ItemsControl for DataGrid.Columns? 我想这样做,因为我想像这样使用这个控件:(我想在创建此控件的实例时定义DataGridTextColumns)

<control:DataGridSelectorControl Grid.Row="1">
        <control:DataGridSelectorControl.DataGridColumnItems>
                <DataGridTextColumn Header="نام"  Width="20"></DataGridTextColumn>
                <DataGridTextColumn Header="ParentID" Width="20"></DataGridTextColumn>
        </control:DataGridSelectorControl.DataGridColumnItems>
    </control:DataGridSelectorControl>

和DataGridColumnItems是一个atachepropery:

  public static readonly DependencyProperty DataGridTextColumnItemsProperty = DependencyProperty.Register("DataTextColumnItems", typeof(DataGridColumn), typeof(DataGridSelectorControl));
    public DataGridColumn DataGridColumnItems
    {
        get
        {
            return (DataGridColumn)GetValue(DataGridTextColumnItemsProperty);
        }
        set
        {
            SetValue(DataGridTextColumnItemsProperty, value);
        }
    }

1 个答案:

答案 0 :(得分:0)

DataGrid.Columns的类型为ObservableCollection,请尝试以下方法:

  public static readonly DependencyProperty DataGridTextColumnItemsProperty=DependencyProperty.Register("DataTextColumnItems", typeof(ObservableCollection<DataGridColumn>), typeof(DataGridSelectorControl)))); 
    public ObservableCollection<DataGridColumn> DataGridColumnItems 
    { 
        get 
        { 
            return (ObservableCollection<DataGridColumn>)GetValue(DataGridTextColumnItemsProperty); 
        } 
        set 
        { 
            SetValue(DataGridTextColumnItemsProperty, value); 
        } 
    }

  <DataGrid  x:Name="grd" ItemsSource="{Binding Source={StaticResource theSource}}" AutoGenerateColumns="False" Columns={Binding DataGridTextColumnItems, RelativeSource={RelativeSource AncestorType=DataGridSelectorControl}}> 
            </DataGrid>