wpf为自定义控件添加属性
2018-02-24 17:31
836 查看
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>
运行,效果如下
但是这样做有问题:Button周围有一大片作用区域,是模板定义得有问题,但如果不这样做的话,
MyUserButton.cs中无法找到对应的
tb控件。试了好久也不得法。如果你把问题解决了,Please @me。
相关文章推荐
- 在VS2008中创建自定义控件(十二)添加在属性窗口中可折叠的属性(二)
- 自定义控件添加自定义属性问题
- 【WPF】自定义控件之依赖属性
- WPF利用依赖属性和命令编写自定义控件
- C#自定义控件添加类似Size一样的结构属性
- 使用declare-styleable给自定义控件添加自定义属性
- 在VS2008中创建自定义控件(九)添加属性
- 3.为自定义控件添加属性
- SilverLight学习笔记--建立Silverlight自定义控件(4)--添加自定义属性
- WPF的自定义控件 依赖属性,DependencyProperty 路由事件RoutedEvent
- 给用户自定义控件添加属性
- c# 自定义控件如何在属性栏添加自定义事件
- 【2016-11-11】【坚持学习】【Day24】【WPF 自定义控件 附加属性 自定义事件】
- 【C#】妈妈再也不用担心自定义控件如何给特殊类型的属性添加默认值了,附自定义GroupBox一枚
- Qt 5.8下自定义控件属性栏属性自我添加
- 在Silverlight自定义控件中添加依赖属性
- Android 两种为自定义控件添加属性的使用方法和区别
- c#创建自定义控件在winform上添加该控件属性为空白
- android 自定义控件 与 属性添加 , 注意android studio 和以前不一样了
- 在VS2008中创建自定义控件(十)添加枚举型属性