我正在使用輕量級樣式來設定按鈕樣式:
<Button ...>
<Button.Resources>
<SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#48B2E9"/>
<SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Black"/>
...
</Button.Resources>
</Button>
我想將此樣式應用于多個(但不是全部)按鈕。
目前我需要將這些復制并粘貼<Button.Resources>到我想要設定樣式的每個按鈕上。
有沒有辦法避免這種重復?
我嘗試創建一種樣式,但不知道如何在樣式中設定資源。
我想我可以創建一個控制模板,但這似乎很重。
uj5u.com熱心網友回復:
Button您可以考慮創建一個Button始終應用資源的自定義控制元件,而不是嘗試設定內置的樣式。
在 Visual Studio 中向專案(專案->添加新項->用戶控制元件)添加一個UserControl,并將 XAML 檔案的內容替換為以下內容:
<!-- MyCustomButton.xaml -->
<Button
x:Class="WinUIApp.MyCustomButton"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Button.Resources>
<SolidColorBrush x:Key="ButtonBackgroundPointerOver" Color="#48B2E9"/>
<SolidColorBrush x:Key="ButtonForegroundPointerOver" Color="Black"/>
</Button.Resources>
</Button>
...并相應地更改代碼隱藏類的基類:
// MyCustomButton.xaml.cs
public sealed partial class MyCustomButton : Button
{
public MyCustomButton()
{
this.InitializeComponent();
}
}
Button然后,您可以像往常一樣在任何其他視圖中創建此實體,例如:
<local:MyCustomButton Content="Click me!" />
<local:MyCustomButton Content="Another button..." />
uj5u.com熱心網友回復:
對誤會深表歉意
您不能在樣式定義上設定資源。因此您必須將附加的 DependencyProperty 添加到按鈕,然后將其設定為樣式定義
看到這個
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/436751.html
