【发布时间】:2019-09-06 05:14:32
【问题描述】:
我正在使用 C# 7、.Net 4.7.2 和 WPF 4.5.2
我想显示分层数据。因此,我使用 ListBox 作为顶级控件,使用 ListView 作为子级控件。无论哪种样式,ListBox的DataTemplate都是这样的
<DataTemplate>
<Border>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding SomeTextProperty}" />
<ListView Grid.Row="1" ItemsSource="{Binding SubDataClasses}"
ItemContainerStyle="{DynmicRessource MyListViewItem}" />
</Grid>
</Border>
</DataTemplate>
在 DataContext 中有一个名为 MyDataSource 的属性,ListBox 的 ItemsSource 绑定到该属性。该属性看起来像这样
public ObservableCollection<MyMainDataClass> MyDataSource { get; set; }
最后但并非最不重要的数据类:
public class MySubDataClass
{
public string SomeValue { get; set; }
}
public class MyMainDataClass
{
public string SomeTextProperty { get; set; }
public ObservableCollection<MySubDataClass> SubDataClasses { get; set; }
}
ListBox 中的绑定工作正常。但是 SomeTextProperty 恰好显示正确。属于每个 MyMainDataClass 的 MySubDataClasses 的数量也是正确的。
但是 SomeValue 的内容根本就没有显示出来。您所看到的只是类 MySubDataClass 的名称。通常,在这种情况下会出现绑定错误,例如绑定中的属性名称拼写错误。不是我的情况。但是,一定有什么地方出错了。
我使用 diag:PresentationTraceSources.TraceLevel=High 检查了绑定。但是 Visual Studio 的输出窗口什么也没有显示。没有信息,没有警告,没有错误。绝对没有什么。在 ListBox 的 ItemsSource 的 Binding 上的相同跟踪显示一切正确。
我还在测试场景中单独尝试了 ListView。工作正常。所以 ListView 本身并没有什么问题,而是作为 ListBox 的子控件。
有人可以帮帮我吗?
提前致谢。
加法:
ListViewItem的样式是这样的
<Style x:Key="MyListViewItem" TargetType="{x:Type ListViewItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<TextBox Text="{Binding SomeValue}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
【问题讨论】:
-
显然没有用于 ListView 的 ItemTemplate 的 DataTemplate。您希望如何显示 SomeValue 属性?只是一个注释,为什么它是一个 ListView (它比 ListBox 更复杂)?你设置它的 View 属性吗?您需要选择支持吗? ItemsControl 可能是更好的选择。
-
正如我之前提到的,ListView 本身工作正常。因此,ItemContainerStyle 设置正确。但确切地说,我将 ListViewItem 的样式定义添加到我的原始帖子中。我确实需要选择支持,我也可能需要 DataGrid RowDetails 之类的东西。但不是马上。我选择 ListView 是因为我认为在需要多列的情况下它可能更容易处理。
-
尽管有错字
DynmicRessource,但为什么将 ItemsContainerStyle 设置为动态资源?以及为什么要设置 ItemContainerStyle 而不是 ItemTemplate?更简单的可能是自动选择的 DataTemplate,其中 DataType 设置为 MySubDataClass。 -
在您的
ListView上,您是否尝试过使用DisplayMemberPath来显示该值? -
"通常,在这种情况下会出现绑定错误"是不正确的。如果您只看到类名,则意味着您的 ItemContainerStyle 根本没有被应用,并且 ListView 使用默认的 ItemContainerStyle 和 ItemTemplate,其中只显示
MySubDataClass.ToString()的结果。