Create Simple Custom XAML / C# button

浪子不回头ぞ 提交于 2019-12-11 18:43:58

问题


First of all, I'm new to XAML / C# (am iOS/Android programmer) so please bear with me instead of immediately voting down. My app has some GridViews that contain buttons. A lot of these buttons are similar and I would like to refactor this. For simplicity let's say my buttons are just Rectangles with a given color. This color might come from the Item class that defines the particular item in the GridView, or it might be hardcoded. I want the rectangle to change color on hover and pressed states. I want these colors to be parameters as well.

What is the best way to achieve this?

  1. I tried to make a Button subclass but somehow I couldn't access the dependency properties in the VisualStateManager
  2. I tried to write stuff in the code-behind but then I wasn't sure how to delegate the click command to the ViewModel class.

Could someone give me a small working example?

Thanks


回答1:


You can do this with style templates.

In the Visual Studio designer, right-click on your button and then select Edit Template and then select Edit a Copy....

You will then be prompted to name your new style and also for which file to store it in. For now, just give it a unique name such as MyButtonStyle, and select the current file.

Visual Studio will then add a copy of the style to the current xaml document, and will update your button to use the new style.

<Button x:Name="Download" Style="{StaticResource MyButtonStyle}"></Button>

After this, you can update the new style including changing the colors for the different visual states such as hover or clicked.

You can then proceed to use the new style in other buttons in the same document. To use the style in multiple xaml documents, you have to pull it out into a common resource file.




回答2:


So you want to adjust your button using custom properties. This is a good time to use a custom control. You can create whatever dependency properties you want and adjust your layout in your code. http://timheuer.com/blog/archive/2012/03/07/creating-custom-controls-for-metro-style-apps.aspx



来源:https://stackoverflow.com/questions/14087801/create-simple-custom-xaml-c-sharp-button

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!