开发者

WPF ComboBox in DataGridTemplateColumn with alternate ItemsSource

I am aware that this topic has come up a few times before, but I have tried the ways that I found here and none seem to work. I don't know if it's because I am using different binding sources, or if I'm just failing, or what...

I have a DataGrid which is bound to an XML document read into memory. I have a List containing all of the distinct values that one column could be and want to use this as the开发者_JAVA技巧 ItemsSource for the ComboBox column.

My XAML is as follows:

<DataGrid AutoGenerateColumns="False" IsReadOnly="False"  Height="400" HorizontalAlignment="Left" Margin="125,15,0,0" x:Name="dg" VerticalAlignment="Top" Width="500">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Width="40*" Binding="{Binding Path=Element[name].Value}" />
        <DataGridTextColumn Header="Count" Width="10*" Binding="{Binding Path=Attribute[count].Value}" />

<!-- I want this to be a ComboBox in a DataGridTemplateColumn -->
        <DataGridTextColumn Header="Category" Width="25*" Binding="{Binding Path=Attribute[category].Value}" /> 

        <DataGridTextColumn Header="Image Path" Width="25*" Binding="{Binding Path=Element[image].Value}" />
    </DataGrid.Columns>
</DataGrid>

And a sample XML node which si displayed would look like this:

<entry count="1" category="someCategory">
    <name>Entry 1</name>
    <image>c:\image.png</image>
</entry>

Finally, the list which I want to use as the ItemsSource for the ComboBoxes:

var categories = from category in xmlDoc.Root.Elements("entry") select category .Attribute("category").Value;
List<string> catList= categories .ToList<string>();

So when a user edits the category field I want them to have a dropdown containing the possible values contained in the list.


EDIT: Finally got this working, I did as stated in the accepted answer, set the ItemsSource of the ComboBox to

ItemsSource="{DynamicResource categoryList}"

and then simply did this in the code after creating the list item I wanted to use to populate the ComboBoxes:

Resources["categoryList"] = catList;


you have to build a DataGridTemplateColumn with a CellTemplate and a CellEditingTemplate. the following should give your the right direction to start

<DataGridTemplateColumn Header="Category" Width="100">
  <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding YourProperty}" />
    </DataTemplate>
  </DataGridTemplateColumn.CellTemplate>
  <DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
      <ComboBox ItemsSource="{Binding YourSource, Mode=OneTime or OneWay}">
      </ComboBox>
    </DataTemplate>
   </DataGridTemplateColumn.CellEditingTemplate>          
 </DataGridTemplateColumn>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜