110,566
社区成员
发帖
与我相关
我的任务
分享
<Button x:Class="UserButtonTest.MyUserButton"
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:UserButtonTest"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Background="Transparent" BorderThickness="0">
<Button.Template>
<ControlTemplate>
<Grid>
<Border Name="border" BorderThickness="3" CornerRadius ="5" Background="#FFFFCC" BorderBrush="#FF6633">
<Border BorderThickness="0" Height="20">
<Viewbox VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Name="tb" Text="DefaultText"></TextBlock>
</Viewbox>
</Border>
</Border>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
#region Text属性
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(MyUserButton),new PropertyMetadata("TextBox",new PropertyChangedCallback(OnTextChanged)));
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
static void OnTextChanged(object sender, DependencyPropertyChangedEventArgs args)
{
((MyUserButton)sender).tb.Text = (string)args.NewValue; // tb 在这里
}
#endregion
MyUserButton self = sender as MyUserButton;
TextBlock tb = self.GetTemplateChild("tb") as TextBlock;
tb.Text = (string)args.NewValue;
方法二,使用WPF绑定特性,绑定到依赖属性上,修改xaml代码:
<TextBlock Name="tb" Text="{Binding Text,RelativeSource={RelativeSource TemplateParent}}"/>