开发者

WPF DataTemplateColumn access DataTemplate and set ItemsSource

开发者 https://www.devze.com 2023-01-19 12:14 出处:网络
I know its strange what I am doing but I want this to work. I am going wrong somehwere I feel. I have a DataTemplate defined in my resources as follows :

I know its strange what I am doing but I want this to work. I am going wrong somehwere I feel.

I have a DataTemplate defined in my resources as follows :

  <UserControl.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="../ParameterEditorResourceDictionary.xaml"></ResourceDictionary>
            <ResourceDictionary>

                <DataTemplate x:Key="ParameterDefault">
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="("></TextBlock>
                        <ItemsControl ItemsSource="{//I need to set from code}">
                            //some code here
                        </ItemsControl>
                        <TextBlock Text=")"></TextBlock>
                    </StackPanel>
                </DataTemplate>

          </ResourceDictionary>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>       
</UserControl.Resources>

I have a DataGrid defined in my xaml which has a loaded event.

 <cc:PEDataGrid AutoGenerateColumns="False"
               Loaded="CommonPEGrid_Loaded">        
</cc:PEDataGrid>

In my event handler code I want to set the ItemsSource of ItemsControl defined in my DataTemplate. My code behind looks like this :

private void CommonPEGrid_Loaded(object sender, RoutedEventArgs e)
    {
        int i = 0;
        DataGrid dg = sender as DataGrid;

        DataGridTemplateColumn column = null;

        //ParametersAllLoops is a ObservableCollec开发者_如何学Ction

        foreach (ParameterLoop obj in ParametersAllLoops)
        {
            column = new DataGridTemplateColumn();
            column.Header = "Loop ( " + i.ToString() + " )";

            DataTemplate dt = null;

            //Here I want to write code
            //I want to access the DataTemplate defined in resources 
            //and set the ItemsSource of ItemsControl to something like this
            // xxx.ItemsSource = obj; and then assign the DataTemplate to 
            //the CellTemplate of column.
            //**Note :: ParameterLoop object has the IList Parameters**


            column.CellTemplate = dt;

            dg.Columns.Add(column);
            i++;            
        }
}


You can find the resource by using method FindResource() and cast it to DataTemplate but to assign it ItemSource you will need string manipulation.

It seems you want to have dynamic columns on your datagrid, I would suggest that you have that generate the datatemplate in code behind so that you can resolve your binding paths and source names there and then attach it as cell template or cell edit template.

0

精彩评论

暂无评论...
验证码 换一张
取 消