【问题标题】:WPF Listbox with wider scrollbars具有更宽滚动条的 WPF 列表框
【发布时间】:2015-02-19 18:43:41
【问题描述】:

我是 WPF 的新手,我需要您的帮助来创建一个 wpf 自定义 ListBox,其滚动条比默认值更宽。

我找到了一个适用于包括 ListBox 的 Window WPF 的解决方案:

<Window x:Class="iFixCustomControlsTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:cc="clr-namespace:iFixCustomControls;assembly=iFixCustomControls"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox HorizontalAlignment="Left" Height="92" Margin="56,88,0,0" VerticalAlignment="Top" Width="357" ScrollViewer.VerticalScrollBarVisibility="Visible"/>
    </Grid>

    <Window.Resources>
        <Style TargetType="ScrollBar">
            <Setter Property="Width" Value="100"/>
        </Style>        
    </Window.Resources>
</Window>

此解决方案不是我最喜欢的解决方案,因为它意味着在包含“经典”列表框的窗口中编写代码。我需要的是一种在 Generic.xaml 中修改 Listbox 内滚动条的方法(如果我理解得很好):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:iFixCustomControls">
    <Style TargetType="local:iFixCustomListBox" BasedOn="{StaticResource {x:Type ListBox}}">
        <!--  
              Setting scrollbar wider than default
              Something like:
              <Style TargetType="ScrollBar">
                  <Setter Property="Width" Value="100"/>
              </Style>
        -->
    </Style>
</ResourceDictionary>

.cs 文件是:

public class iFixCustomListBox : ListBox
{
    static iFixCustomListBox()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(iFixCustomListBox), new FrameworkPropertyMetadata(typeof(iFixCustomListBox)));
    }
}

这种方法是正确的还是更好的方法应该涉及用户控件而不是自定义控件?

【问题讨论】:

  • 您是否在询问如何在您的应用程序中为 all ListBox 控件设置滚动条宽度?
  • 没有。长话短说:我在问如何扩展 ListBox 并更改滚动条宽度。
  • 那将是一个很好的问题标题;o)。无论如何,我已经发布了一个可能对您有所帮助的答案。

标签: c# wpf custom-controls


【解决方案1】:

如果我对您的理解正确,您有一个从 ListBox 派生的自定义控件类型,并且您希望该控件的每个实例都具有更宽的垂直滚动条。

如果是这样,您可以为您的控件使用自定义样式(您可能已经有),并将ScrollBar 样式添加到那个 样式的Resources 集合:

<Style TargetType="{x:Type local:iFixCustomListBox}">
    <Style.Resources>
        <Style TargetType="{x:Type ScrollBar}">
            <Setter Property="Width" Value="100" />
        </Style>
    </Style.Resources>
</Style>

我尝试将这种样式放置在 (a) 窗口和 (b) 应用程序的资源集合中,并且在这两种情况下都可以正常工作,所以我认为如果放置在 generic.xaml 中它也可以工作。

【讨论】:

  • 我之前尝试过这个解决方案,但没有成功:显示一个未配置的列表框。这是因为我忘记了 Style 块中的 BasedOn="{StaticResource {x:Type ListBox}}"
  • 奇怪,没有BasedOn 属性对我来说效果很好(虽然我没有在generic.xaml 中尝试过,也许这就是区别)。
【解决方案2】:

这个怎么样?

<ScrollViewer Width="100">
      <ListBox ...>
</ScrollViewer>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-17
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    相关资源
    最近更新 更多