//自定义canvas 布局
//自定义canvas 布局 class CustomCanvas : Canvas { public static readonly DependencyProperty Text2InheritProperty = DependencyProperty.RegisterAttached("Text2Inherit", // 注册附加属性 typeof(string), typeof(CustomCanvas), new FrameworkPropertyMetadata("DefaultTextOfCanvas", FrameworkPropertyMetadataOptions.Inherits)); //设置依赖属性的默认值 public string Text2Inherit { set { SetValue(Text2InheritProperty, value); } get { return (string)GetValue(Text2InheritProperty); } } }
// 自定义Button控件
class CustomButton : Button { public static readonly DependencyProperty Text2InheritProperty; //依赖属性 public string Text2Inherit { set { SetValue(Text2InheritProperty, value); } //新设置属性值保存在本地的effectiveValue集合中存放 get { return (string)GetValue(Text2InheritProperty); } } static CustomButton() { //设置的依赖属性值的继承 Text2InheritProperty = CustomCanvas.Text2InheritProperty.AddOwner(//添加多个依赖属性的共享者 typeof(CustomButton), new FrameworkPropertyMetadata("DefaultTextOfButton", FrameworkPropertyMetadataOptions.Inherits)); } }
主界面上的使用
<Grid> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <local:CustomCanvas x:Name="canvas0" Width="500" Grid.Row="0"> <StackPanel Orientation="Horizontal"> <TextBlock Text="Default Text2Inherit of CustomCanvas is: "/> <TextBlock x:Name="textBlock1"/> </StackPanel> </local:CustomCanvas> <local:CustomCanvas x:Name="canvas1" Width="500" Grid.Row="1"> <StackPanel Orientation="Horizontal"> <TextBlock Text="Default Text2Inherit of CustomButton is: "/> <local:CustomButton x:Name="button1"/> </StackPanel> </local:CustomCanvas> <local:CustomCanvas x:Name="canvas2" Width="500" Grid.Row="2" Text2Inherit="TEXT from Canvas!!!"> <StackPanel Orientation="Horizontal"> <TextBlock Text="After inheriting,Text2Inherit is: "/> <local:CustomButton x:Name="button2"/> </StackPanel> </local:CustomCanvas> </Grid>
运行结果