我正在嘗試創建一個以按鈕開頭的用戶控制元件庫。我設法使用如下所示的代碼創建了一個 button.xaml;
<UserControl x:Class="SPECTRE.UserControls.Buttons.button"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SPECTRE.UserControls.Buttons"
mc:Ignorable="d"
Height="Auto" Width="Auto"
x:Name="RootElement">
<UserControl.Resources>
<Style x:Key="DangerButton" TargetType="{x:Type Button}">
<Setter Property="MinWidth" Value="100"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="Height" Value="35"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Background" Value="#F12427"/>
<Setter Property="Foreground" Value="White"/>
<Setter Property="FontSize" Value="15"/>
<!--<Setter Property="Content" Value="Go"/>-->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="5">
<ContentPresenter
HorizontalAlignment="Center"
VerticalAlignment="Center"
TextBlock.Foreground="{TemplateBinding Foreground}"
Margin="0,0,0,5"
Content="Button Text"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#D6E006"/>
<Setter Property="Cursor" Value="Hand"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<StackPanel>
<!--Content should be dynamic-->
<Button Style="{StaticResource DangerButton}" Name="button1"/>
</StackPanel>
我有一個用戶控制檔案 video.xaml,其中按鈕實體化如下;
<Buttons:button/>
我正在嘗試使按鈕內容動態化,但似乎無法正確處理。我在這里嘗試過,但它無法正常作業。我需要做什么?
uj5u.com熱心網友回復:
您在那里定義的唯一自定義內容是Style. 移動StyletoApp.xaml或另一個資源字典,然后簡單地將 替換UserControl為Button元素:
<Button Style="{StaticResource DangerButton}" Name="button1" Content="Content..."/>
另一種選擇可能是創建一個DangerButton繼承自的自定義控制元件Button:
public class DangerButton : Button
{
static DangerButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(DangerButton),
new FrameworkPropertyMetadata(typeof(DangerButton)));
}
}
Style在這種情況下,您應該在名為 (按約定) 的資源字典中定義控制元件的默認值themes/generic.xaml。
所以把你的電流移到Style那里并從中移除x:Key="DangerButton"。然后,您可以像這樣使用自定義控制元件:
<Buttons:DangerButton Content="Content..." />
如果您選擇簡單地將 包裝Button在 a 中UserControl,您將無法Button直接從使用UserControl. 然后,您必須將屬性添加到UserControl并將它們系結到Button.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/458853.html
