【问题标题】:How to bind a list<string> to DataGridColumn?如何将 list<string> 绑定到 DataGridColumn?
【发布时间】:2012-03-26 11:16:28
【问题描述】:

我有以下 XAML:

<DataGrid Name="nodeDataGrid" ItemsSource="{Binding NodeList}" AutoGenerateColumns="False" RowBackground="White"
            AlternatingRowBackground="AliceBlue" Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
            Background="Silver" Margin="0,34,10,10" IsReadOnly="True" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Path=Name}" CanUserSort="True" SortDirection="Ascending" CellStyle="{StaticResource CellStyle}" />
            <DataGridTextColumn Header="Category" Binding="{Binding Path=Category}" Width="*" />
            <DataGridTemplateColumn Header="Children">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <ListBox>
                            <TextBlock Text="{Binding}" />
                        </ListBox>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

还有后面的代码:

    private ServiceMapViewModel smViewModel = new ServiceMapViewModel();

    public MainWindow()
    {
        InitializeComponent();
        this.Loaded += (s, e) =>
            {
                this.DataContext = smViewModel;

            };
    }

在 ServiceMapViewModel 我有一个 NodeList 像: List

而节点是:

    public string Name { get; set; }

    public string Category { get; set; }

    public string Group { get; set; }

    public List<string> Children { get; set; }

    public List<string> Parents { get; set; }

我的问题是如何将列表框绑定到 Chidren 属性?

【问题讨论】:

  • 你试过ItemSource={Binding Children}
  • 是的,我试过了,但是抛出了一个异常,因为 ItemsSource 已经在数据网格中初始化了

标签: c# .net wpf silverlight binding


【解决方案1】:

Children 是当前上下文的集合,因此您需要使用以下内容:

<ListBox ItemsSource="{Binding Children}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <TextBlock Text="{Binding}" />
     </DataTemplate>
   </ListBox.ItemTemplate> 
</ListBox>

【讨论】:

  • TNX 它的工作。在我的时区为时已晚,所以我的大脑停止工作。我在没有任何模板的列表框中写了一个文本块-.-
【解决方案2】:
<TextBlock Text="{Binding Children}" />

但是请注意,除非您在 Node 类上实现 INotifyPropertyChanged,否则您不会获得对绑定中反映的属性的更新。

编辑:哦,等等,您正在将一个数组绑定到一个数组中。然后,您将需要一个可以实际绑定集合而不是 TextBlock 的控件。或者你想只绑定一个节点?

也许您可以更好地解释一下您要做什么。

【讨论】:

  • 不幸的是,这行不通。是的,我已经在 ViewModel 中实现了 INotifyPropertyChaned,并且我有一个正确的 Name 和 Category DatagridColumn 值!编辑:它显示为(集合)
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 2021-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多