我有一个用作控件作为按钮。我希望此按钮的用户能够在设计时通过Visual Studio中的“属性”窗口设置控件内部标签中的文本,此时他们将此控件放在表单或其他任何内容上。具体来说,我的意思是我希望他们能够将控件放在表单上,单击所述控件,然后在属性窗口中查看类似Text的内容并能够为标签提供文本。我不确定要搜索什么,因为它是一个复杂的问题,希望有一个简单的答案。有谁知道我需要添加到我的代码或XAML来实现这一目标?
以下是完整性的XAML:注意标签的content属性。
<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>
答案 0 :(得分:1)
要通过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));
元数据的最后一个参数是change事件处理程序,并且是可选的。在控件的Loaded
事件中,您可以将标签文本设置为Text
。如果要支持绑定更新,可以包含更改事件处理程序并在那里进行更新。