wpf為自定義控件添加屬性
首先,建立
UserControl.xaml
檔案,命名為
MyUserButton
,之後改成這種樣式
<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">
<Grid>
<Border Height="50" BorderThickness="3" CornerRadius ="5" Background="#FFFFCC" BorderBrush="#FF6633">
<Border BorderThickness="0">
<Viewbox VerticalAlignment="Center" HorizontalAlignment="Center">
<TextBlock Name="tb" Text="Default Text"></TextBlock>
</Viewbox>
</Border>
</Border>
</Grid>
</Button>
打開對應的
.cs
檔案,做如下修改
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(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
((MyUserButton)sender).OnValueChanged(args);
}
protected void OnValueChanged(DependencyPropertyChangedEventArgs e)
{
this.tb.Text = e.NewValue.ToString();
}
然後在
MainWindow.xaml
中引用這個控件
<local:MyUserButton Text="ddd" Width="200" Height="100" ClickF="MyUserButton_ClickF"></local:MyUserButton>
運作,效果如下