创建简单的自定义 XAML/C# 按钮 [英] Create Simple Custom XAML / C# button

查看:27
本文介绍了创建简单的自定义 XAML/C# 按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我是 XAML/C# 的新手(我是 iOS/Android 程序员)所以请耐心等待,而不是立即投票反对.我的应用程序有一些包含按钮的 GridViews.许多这些按钮是相似的,我想重构它.为简单起见,假设我的按钮只是具有给定颜色的矩形.此颜色可能来自在 GridView 中定义特定项目的 Item 类,或者它可能是硬编码的.我希望矩形在悬停和按下状态时改变颜色.我希望这些颜色也成为参数.

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. 我尝试创建一个 Button 子类,但不知何故我无法访问 VisualStateManager 中的依赖属性
  2. 我尝试在代码隐藏中编写内容,但我不确定如何将点击命令委托给 ViewModel 类.

有人能给我一个小的工作示例吗?

Could someone give me a small working example?

谢谢

推荐答案

您可以使用样式模板来做到这一点.

You can do this with style templates.

在 Visual Studio 设计器中,右键单击您的按钮,然后选择 Edit Template,然后选择 Edit a Copy....

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

然后系统会提示您命名新样式以及将其存储在哪个文件中.现在,只需为其指定一个唯一名称,例如 MyButtonStyle,然后选择当前文件.

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 然后会将该样式的副本添加到当前的 xaml 文档中,并将更新您的按钮以使用新样式.

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.

然后您可以继续在同一文档的其他按钮中使用新样式.要在多个 xaml 文档中使用该样式,您必须将其拉出到一个公共资源文件中.

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.

这篇关于创建简单的自定义 XAML/C# 按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆