【发布时间】:2016-01-21 04:02:15
【问题描述】:
我在这里倾注了答案和例子,但似乎没有一个能解决我的问题。
我有一个带有 TextBlock 和 ComboBox 的典型 DataGridTemplateColumn:
<DataGridTemplateColumn Header="Section" SortMemberPath="SectionName" CanUserSort="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding SectionName}">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding SectionName, Converter={StaticResource SectionBackgroundConverter}}"/>
<Setter Property="Padding" Value="5,5,5,5"></Setter>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate >
<DataTemplate >
<ComboBox x:Name="cmbSections" ItemsSource="{Binding Path=g_colZDSectionNames}" SelectedItem="{Binding SectionName}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
TextBlock 绑定到绑定到 DataGrid 的对象列表中的一个对象。它按预期显示其属性。
ComboBox 需要绑定到在运行时未知的字符串集合,直到函数调用 Web 服务来获取值。然后,我将另一个不在 DataGrid 中的名为 cmbDefaultSections 的 ComboBox 绑定到以下 ZDSection 对象。它按预期显示列表。但是,如果我将 DataGrid 中名为 cmbSections 的 ComboBox 绑定到同一个对象,或者按照建议将其绑定到 ObservableCollection(Of String) ,则它仍然为空。我怀疑这是因为在运行时创建 ComboBox 时名为 Sections 的 DynamicResource 是 Nothing,正如预期的那样。
在我的代码隐藏中,我正在设置另一个 ComboBox 的 ItemsSource,如下所示:
cmbDefaultSections.ItemsSource = New ZDSections.ZDSection
现在如何类似地设置 cmbSections?它无法从代码中访问。我尝试在集合对象上实现 INotifyCollectionChanged 以便它自动更新,但无济于事:
Public Class ZDSection
Inherits ObservableCollection(Of String)
Implements INotifyCollectionChanged
Public Sub New()
If g_lstZDSections IsNot Nothing Then
For Each section In g_lstZDSections
Me.Add(section.Name)
Next section
Call OnCollectionChanged(New NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))
End If
End Sub
Public Shadows CollectionChanged As NotifyCollectionChangedEventHandler
Protected Overrides Sub OnCollectionChanged(e As NotifyCollectionChangedEventArgs)
MyBase.OnCollectionChanged(e)
If CollectionChanged IsNot Nothing Then
CollectionChanged.Invoke(Me, e)
End If
End Sub
End Class
提前感谢您的建议!
【问题讨论】: