我有一个带有一些模板的列表框。组由扩展器表示。列表框链接到文件系统,每个文件夹都有自己的扩展器。每当文件被重命名、删除等时,列表框的 View 都会刷新。这很好用,但是一旦调用刷新,每个扩展器都会崩溃。我似乎找不到让它们保持打开状态的好方法。我看到另一个问题使用绑定(bind)来解决单个扩展器的问题。 “IsExpanded”上数据绑定(bind)的问题是扩展器的数量未知,我无法知道在设计时会有多少,它们将被称为什么等等。有什么想法吗?
<ListBox.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander VerticalAlignment="Top"
OverridesDefaultStyle="True"
Template="{StaticResource SimpleExpanderTemp}">
<Expander.Header>
<TextBlock VerticalAlignment="Center"
Background="Transparent"
Text="{Binding Path=Name}"
FontFamily="SegoeUI"
FontSize="16"
Foreground="Black"/>
</Expander.Header>
<Expander.Tag>
<LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0.0" Color="#696969" />
<GradientStop Offset="1.0" Color="#474747" />
</LinearGradientBrush>
</Expander.Tag>
<ItemsPresenter/>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListBox.GroupStyle>
最佳答案
一种可能的解决方案是仍然对 IsExpanded 属性使用数据绑定(bind)。
不是绑定(bind)到 bool 值,而是绑定(bind)到 bool 值列表并使用 ValueConverter 从列表中检索适当的项目。
在创建所有扩展器时,给每个扩展器一个索引号(如果您还没有的话)。然后在绑定(bind)IsExpanded属性时,设置Converter,将converter参数设置为expander的索引号。然后您的转换器将收到 bool 值列表作为“值”参数,索引号作为“参数”参数,然后您的转换器可以返回一个 bool 值。
您的转换器可能如下所示:
public class ListToBooleanConverter : IValueConverter
{
public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((value != null) & (parameter != null)) {
try {
Int16 itmNum = Convert.ToInt32(parameter);
List<bool> lst = value;
return lst[itmNum];
} catch (Exception ex) {
return null;
}
}
return null;
}
public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException("This method or operation is not implemented.");
}
}
在 XAML 中,此数据绑定(bind)和转换器的实现如下所示(对于索引号为 5 的扩展器):
IsExpanded="{Binding Path=ListIsExpanded, Converter={StaticResource ListToBooleanConverter}, ConverterParameter=5}">
显然,在代码中,这个实现看起来会有点不同。
关于c# - 源重置后扩展器分组崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11636319/