我有一个充当按钮的用户控件。我希望此按钮的用户能够在设计时通过 Visual Studio 中的"属性"窗口在控件的内部标签中设置文本,当他们将此控件放在窗体或其他任何内容上时。具体来说,我的意思是我希望他们能够将控件放在窗体上,单击所述控件,然后在属性窗口中看到类似 Text 的内容,并能够为标签提供文本。我真的不确定要搜索什么,因为这是一个复杂的问题,希望有一个简单的答案。有谁知道我需要向我的代码或 XAML 添加什么才能完成此操作?
下面是用于完整性的 XAML:请注意标签的内容属性。
<UserControl x:Class="CartControllerForms.UserControls.TileButton"
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"
mc:Ignorable="d" Height="81" Width="364">
<Border BorderBrush="#FF000000" BorderThickness="1,1,1,1" CornerRadius="8,8,8,8">
<Border.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop x:Name="Stop1" Color="Black" Offset="0"/>
<GradientStop x:Name="Stop2" Color="#FF666262" Offset="0.843"/>
</LinearGradientBrush>
</Border.Background>
<Grid Margin="9" HorizontalAlignment="Center" VerticalAlignment="Center" Height="61" Width="344">
<Label x:Name="TextLabel" HorizontalAlignment="Center" Margin="10,16,10,19" VerticalAlignment="Center"
Width="324" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="Verdana"
FontSize="16" FontWeight="Bold" Foreground="#FFB8BCBD" Content="I want this exposed"/>
</Grid>
</Border>
<UserControl.Triggers>
<EventTrigger RoutedEvent="Border.MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="Stop2" Storyboard.TargetProperty="Color" To="Blue" Duration="0" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="Border.MouseLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetName="Stop2" Storyboard.TargetProperty="Color" To="#FF666262" Duration="0" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</UserControl.Triggers>
</UserControl>
若要通过 XAML(或设计器)获取可用的属性,需要将其公开为DependencyProperty
。最简单的方法是通过propdp
片段。
下面是一个样子:
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
// Using a DependencyProperty as the backing store for Value. This enables animation, styling, binding, etc...
public static readonly DependencyProperty TextProperty=
DependencyProperty.Register("Text", typeof(string), typeof(MyButton), new PropertyMetadata("", HandleValueChange));
元数据上的最后一个参数是更改事件处理程序,并且是可选的。在控件的 Loaded
事件中,将标签文本设置为 Text
。如果要支持绑定更新,则应包含更改事件处理程序并在其中进行更新。