【发布时间】:2010-11-29 10:01:57
【问题描述】:
您好!
我在我的项目(Silverlight 3 with C#)中遇到了这个问题:
我有一个 TreeView,它是数据绑定到树上的。 这个 TreeView 在资源字典中有一个 HierarchicalDataTamplate,它定义了各种控件。现在我想根据节点是否有子节点来隐藏(Visibility.Collapse)一些项目。其他项目应在相同条件下可见。
当我第一次将源代码树绑定到 TreeView 时,它就像魅力一样,但是当我更改源代码树时,树视图中的可见性不会改变。
XAML - 页面:
<controls:TreeView x:Name="SankeyTreeView"
ItemContainerStyle="{StaticResource expandedTreeViewItemStyle}"
ItemTemplate="{StaticResource SankeyTreeTemplate}">
<controls:TreeViewItem IsExpanded="True">
<controls:TreeViewItem.HeaderTemplate>
<DataTemplate>
<TextBlock Text="This is just for loading and will be replaced directly after the data becomes available..."/>
</DataTemplate>
</controls:TreeViewItem.HeaderTemplate>
</controls:TreeViewItem>
</controls:TreeView>
XAML - 资源字典
<!-- Each node in the tree is structurally identical, hence only one Hierarchical
Data Template that'll use itself on the children. -->
<Data:HierarchicalDataTemplate x:Key="SankeyTreeTemplate"
ItemsSource="{Binding Children}">
<Grid Height="24">
<TextBlock x:Name="TextBlockName" Text="{Binding Path=Value.name, Mode=TwoWay}"
VerticalAlignment="Center" Foreground="Black"/>
<TextBox x:Name="TextBoxFlow" Text="{Binding Path=Value.flow, Mode=TwoWay}"
Grid.Column="1" Visibility="{Binding Children,
Converter={StaticResource BoxConverter},
ConverterParameter=\{box\}}"/>
<TextBlock x:Name="TextBlockThroughput" Text="{Binding Path=Value.throughput, Mode=TwoWay}"
Grid.Column="1" Visibility="{Binding Children,
Converter={StaticResource BoxConverter}, ConverterParameter=\{block\}}"/>
<Button x:Name="ButtonAddNode"/>
<Button x:Name="ButtonDeleteNode"/>
<Button x:Name="ButtonEditNode"/>
</Grid>
</Data:HierarchicalDataTemplate>
现在,如您所见,TextBoxFlow 和 TextBlockThroughput 共享相同的空间。 我的目标是:节点的“吞吐量”值是有多少东西从其子节点“流”过该节点。不能直接更改,所以我想显示一个文本块。只有叶节点有一个 TextBox 让某人输入在这个叶节点中生成的“流”。 (即:Node.Throughput = Node.Flow + Sum(Children.Throughput),其中每个非叶节点的 Node.Flow = 0。)
BoxConverter(愚蠢的名字-.-)做了什么:
public object Convert(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
if ((value as NodeList<TreeItem>).Count > 1) // Node has Children?
{
if ((parameter as String) == "{box}")
{
return Visibility.Collapsed;
}
else ((parameter as String) == "{block}")
{
return Visibility.Visible;
}
}
else
{
/*
* As above, just with Collapsed and Visible switched
*/
}
}
绑定到 TreeView 的树的结构本质上是从Dan Vanderboom 偷来的(有点太多,在这里转储整个代码),除了我这里当然使用 ObservableCollection 用于子项和值项实现 INotifyPropertyChanged。
如果有人能向我解释一下,为什么将项目插入底层树不会更新框和块的可见性,我将不胜感激。
提前谢谢你!
【问题讨论】:
-
这个绑定“Children”是 ObservableCollection 的子类,因此应该提供自动集合更新通知。
标签: c# silverlight silverlight-3.0 binding