【问题标题】:WPF ComboBox in DataGridTemplateColumn with alternate ItemsSource带有备用 ItemsSource 的 DataGridTemplateColumn 中的 WPF 组合框
【发布时间】:2011-03-23 01:23:32
【问题描述】:

我知道这个话题之前已经出现过几次,但我已经尝试了我在这里找到的方法,但似乎都没有。我不知道是因为我使用了不同的绑定源,还是我只是失败了,还是什么...

我有一个绑定到读入内存的 XML 文档的 DataGrid。我有一个列表,其中包含一列可能是的所有不同值,并且希望将其用作 ComboBox 列的 ItemsSource。

我的 XAML 如下:

<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>

显示的示例 XML 节点如下所示:

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

最后,我想用作组合框的 ItemsSource 的列表:

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

因此,当用户编辑类别字段时,我希望他们有一个下拉列表,其中包含列表中包含的可能值。


编辑:终于得到了这个工作,我按照接受的答案中的说明做了,将 ComboBox 的 ItemsSource 设置为

ItemsSource="{DynamicResource categoryList}"

然后在创建我想用来填充组合框的列表项后在代码中简单地执行此操作:

Resources["categoryList"] = catList;

【问题讨论】:

    标签: c# wpf data-binding datagrid


    【解决方案1】:

    您必须使用 CellTemplate 和 CellEditingTemplate 构建 DataGridTemplateColumn。以下应该为您提供正确的开始方向

    <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>
    

    【讨论】:

    • 谢谢,这让我走上了正轨……我将发布最终作为编辑的内容。
    猜你喜欢
    • 2013-06-30
    • 1970-01-01
    • 2012-04-21
    • 1970-01-01
    • 2011-09-06
    • 2021-03-16
    • 2023-03-18
    • 2010-12-17
    • 1970-01-01
    相关资源
    最近更新 更多