简体   繁体   English

Wpf:如何创建自定义 ListBox 控件

[英]Wpf: How can I create a custom ListBox Control

I wanted to create a menu bar in wpf like the ones on websites.我想在 wpf 中创建一个菜单栏,就像网站上的菜单栏一样。 It should have different menu items and per click you get to another page.它应该有不同的菜单项,每次点击你都会进入另一个页面。 The main point is, it should change the borders when hovering or clicking an item.重点是,它应该在悬停或单击项目时更改边框。 So I thought a custom Listbox would be the best solution for my case.所以我认为自定义列表框将是我的案例的最佳解决方案。 I don't want a usercontrol, it should be a custom control.我不想要一个用户控件,它应该是一个自定义控件。

What I have: I created a class that derives from ListBox:我所拥有的:我创建了一个派生自 ListBox 的类:

public class MenuListBox : ListBox
{
    public MenuListBox()
    {

    }
}

And created a resource dictionary to template the listbox.并创建了一个资源字典来模板化列表框。 I also added this as merged dictionary into the generic.xaml file.我还将它作为合并字典添加到 generic.xaml 文件中。

<ResourceDictionary>

<Style TargetType="ListBoxItem">
    <Setter Property="SnapsToDevicePixels" Value="true"/>
    <Setter Property="OverridesDefaultStyle" Value="true"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                ...
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="Controls:MenuListBox" BasedOn="{StaticResource {x:Type ListBox}}">
</Style>
</ResourceDictionary>

At this point I don't know how to continue.此时我不知道如何继续。 The box should also fire an event so I can change a page in frame or something.该框还应该触发一个事件,以便我可以在框架或其他内容中更改页面。 Does anyone know a good solution or any articles / tutorials?有谁知道一个好的解决方案或任何文章/教程? Thanks谢谢

WPF already has a menu object so there is no need for a custom control. WPF 已经有一个菜单对象,因此不需要自定义控件。 Create a custom style for the menu and add it to your application resources.为菜单创建自定义样式并将其添加到您的应用程序资源中。

See here for help on styling a menu: http://www.jimnuzzi.com/2008/06/29/wpf-xaml-menuitem-styles/有关样式菜单的帮助,请参见此处: http : //www.jimnuzzi.com/2008/06/29/wpf-xaml-menuitem-styles/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM