【发布时间】:2015-03-25 04:09:21
【问题描述】:
我正在树视图中显示一个小模型(调查)。节点(=答案)有复选框,加载调查时,标记的答案(属性“IsSelected”= true)被成功检查。
我遇到的麻烦是在初始加载时扩展“IsSelected”= true 的那些节点。我尝试使用一种样式来完成此操作,但无法使其正常工作。例如,请参阅以下样式:
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding Path=IsSelected}">
</Setter>
</Style>
</TreeView.ItemContainerStyle>
这看起来不错(至少对我来说),但它没有效果 - 我猜 datacontext 有问题并且绑定无法掌握正确的“IsSelected” - 那应该是我也绑定的那个复选框。 如何获得正确的数据上下文并扩展这些节点?非常感谢您的帮助或提示!
为了完整起见,这里是树视图的完整 xaml:
<TreeView ItemsSource="{Binding QuestionTree}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Question}" ItemsSource="{Binding Converter={StaticResource QuestionConverter}}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:Group}" ItemsSource="{Binding Options}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:GroupOption}" ItemsSource="{Binding Options}">
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Path=Name}"
IsChecked="{Binding Path=IsSelected}"/>
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MainOption}" ItemsSource="{Binding MainOptions}">
<StackPanel Orientation="Horizontal">
<CheckBox Content="{Binding Path=Name}"
IsChecked="{Binding Path=IsSelected}"/>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding Path=IsSelected}">
</Setter>
</Style>
</TreeView.ItemContainerStyle>
还有我的小模型:
public class Question
{
public string Name { get; set; }
public List<MainOption> MainOptions { get; set; }
public List<Group> Groups { get; set; }
}
public class MainOption
{
public string Name { get; set; }
public int MetaItemId { get; set; }
public bool IsSelected { get; set; }
}
public class Group
{
public string Name { get; set; }
public List<GroupOption> Options { get; set; }
}
public class GroupOption
{
public string Name { get; set; }
public int MetaItemId { get; set; }
public bool IsSelected { get; set; }
}
【问题讨论】:
-
你没有在任何地方使用 INotifyPropertyChanged...没有那个 WPF 不知道属性已经改变
-
嗯,没有任何变化。我说的是初始显示。加载后,我希望树视图扩展所有“已检查”的项目。它适用于“已检查”属性..