【问题标题】:WPF Datagrid with databinding, changing ItemsSource带有数据绑定的 WPF Datagrid,更改 ItemsSource
【发布时间】:2013-08-01 11:41:47
【问题描述】:

我在 WPF 中有一个数据网格,它显示了一些数据的网格。从 ViewModel 中检索数据,该 ViewModel 包含以下属性:

Public ReadOnly Property Devices() As List(Of Device)
    Get
        Return FDevices
    End Get

.

Public ReadOnly Property ClientNetworks() As List(Of network)
    Get
        Return fnetwork
    End Get
End Property

在构建视图模型后,这两个属性都填充了数据。 要使用 Datagrid 中的属性,我使用以下 XAML。

<DataGrid  ItemsSource="{Binding Devices}" AutoGenerateColumns="False" >
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Customer" >
                <DataGridTemplateColumn.CellTemplate >
                    <DataTemplate>
 ------------------   <TextBlock Text="{Binding ClientNetwork.Description}"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
                <DataGridTemplateColumn.CellEditingTemplate>
                    <DataTemplate>
 ------------------>  <ComboBox ItemsSource="{Binding ClientNetwork}" DisplayMemberPath="Description"/>
                    </DataTemplate>
                </DataGridTemplateColumn.CellEditingTemplate>
            </DataGridTemplateColumn>
</DataGrid>

这应该在编辑时显示一个带有描述的文本框和一个带有字符串的组合框。

在 Datagrid 之外,组合框可以正常工作。我知道这是因为 Datagrid 上设置了 ItemsSource,但我似乎找不到如何使它工作。我已经尝试了对组合框代码的几种更改,但到目前为止都没有奏效。

目标是让用户能够编辑单元格并显示一个组合框,他可以从中选择一个字符串,然后将相应的 int 保存在数据库中。

更新 1

<ComboBox ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}},Path=DataContext.ClientNetworks}"
                                  DisplayMemberPath="Description"
                                  SelectedItem="{Binding ClientNetwork}"
                                  />

这就是我修复数据上下文其余部分的方法

【问题讨论】:

    标签: wpf vb.net data-binding datacontext itemssource


    【解决方案1】:

    我找到了完成它的方法,但我不确定这是否应该完成

    <Window.Resources>
        <CollectionViewSource Source="{Binding ClientNetworks}" x:Key="clientnetworks" />
    </Window.Resources>
    

    在组合框中

    <ComboBox ItemsSource="{Binding Source={StaticResource clientnetworks}}" DisplayMemberPath="Description" />
    

    【讨论】:

    • 点击几下,果然所有记录都开始变化,编辑一行时,其他的也变化
    猜你喜欢
    • 1970-01-01
    • 2011-12-17
    • 2011-07-10
    • 2019-03-23
    • 2011-07-21
    • 2017-02-24
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多