简体   繁体   中英

Creating a reusable interface element in WPF

I'm developing a WPF application in C# and was thinking about implementing a custom UI element accross various windows.

I would like to have a minimized tray (only about 4px visible) that expands after clicking on an icon next to the tray. The expanded version would show all controls and would minimize when I click the icon again. I created a quick HTML concept to clarify things.

I know I could put a stackpanel and button in my application and making both of them move up when I click the button, but then I would need to duplicate the code a lot.

Though I'm experienced with C#, I'm fairly new to WPF interface development/templates, but I'm sure there has to be a way so I can use that UI element accross my application without needing to copy/paste a lot of lines of code in my form class file.

I hope someone can help me, or at least point me in the right direction.

There are three ways to customize your elements.

1 If you only need visual modifications you can use styles to change the appearance of the .net default controls. You can even override / extend the default templates.

2 If you want custom logic in a control you can create a custom control . The framework brings a lot of "primitives" to build upon. Examples are ContentControl or HeaderedContentControl . Say you want to build a custom expander control you can inherit your custom control from HeaderedContentControl which provides you with Header and Content properties and you just have to implement the toggling logic yourself. CustomControls are a good choice if you want to build basic functionality which can be used throughout your application. They can be themed/styled depending on the use case, too (see 1).

3 If you want to compose different controls into one control you can create a UserControl . User controls are composed using XAML. Most top level controls are user controls driven by a view model.

Your case can be build using a Popup and ToggleButton or an Expander .

The decision depends on the desired behavior. If you want the opened panel to move following content down you need a expander. If you want a dropdown like functionality you need popup.

If you use a popup just bind the IsPopupOpen Property to IsChecked of the ToggleButton and set PopupStaysOpen = false to wire the button to your popup.

If you use an expander control you should create a style which can be applied to all equal expanders in your application to minimize the required XAML in each view.

如何使用扩展器控件?

There's a control called an Expander that is perfect for this. You'll have to style it to look like you want, however it has the functionality you want built-in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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