我在ListBox之上构建一个Logger控件,我很难让Logger工作(即ListBox滚动)。这是我正在使用的代码:
资源字典中的样式定义:
<Style TargetType="local:Logger">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border x:Name="LayoutRoot">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Head}" Margin="4"/>
<TextBlock Grid.Column="1" Text="{Binding Body}" Margin="4" TextWrapping="Wrap"/>
</Grid>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
定义Logger的C#对应物:
public class LoggerMessage
{
public string Head { get; set; }
public string Body { get; set; }
}
public class Logger : ListBox
{
private ObservableCollection<LoggerMessage> _log;
public Logger() : base()
{
DefaultStyleKey = typeof(Logger);
_log = new ObservableCollection<LoggerMessage>();
for (int i = 0; i < 30; i++)
{
_log.Add(new LoggerMessage() { Head = "Msg: " + i, Body = "Some really long text which hopefully wraps around." });
}
this.ItemsSource = _log;
}
public void log(LoggerMessage item)
{
_log.Add(item);
}
}
经过一番研究和反复试验后,我想出了解决问题的样式模板(见下文)但是,我无法理解为什么它在版本1中不起作用。为什么我必须明确“重新定义”ControlTemplate中的ScrollViewer
<Style TargetType="local:Logger">
<!-- Begin - Redef of ControlTemplate -->
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:Logger">
<ScrollViewer x:Name="ScrollViewer" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Foreground="{TemplateBinding Foreground}" Padding="{TemplateBinding Padding}">
<ItemsPresenter/>
</ScrollViewer>
</ControlTemplate>
</Setter.Value>
</Setter>
<!-- End - Redef of ControlTemplate -->
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="{Binding Head}" Margin="4"/>
<TextBlock Grid.Column="1" Text="{Binding Body}" Margin="4" TextWrapping="Wrap"/>
</Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
提前感谢任何解释。
亲切的问候
答案 0 :(得分:0)
在MSDN文档(DefaultStyleKey)中进行了一些挖掘后,似乎将控件的样式应用于完全覆盖。似乎基类的样式不是像我假设的那样继承的。该文件没有明确说明,但上述实验分类导致了这种理解。