我想创建一个可以在Button Content的位置使用的自定义依赖项属性。请帮助我。
这是我的依赖属性 -
public class MyControl:Button
{
public static readonly DependencyProperty MyCustomControlProperty =
DependencyProperty.Register("SourceC", typeof(string), typeof(MyControl), new UIPropertyMetadata("my button"));
public string SourceC
{
get { return (string)GetValue(MyCustomControlProperty); }
set { SetValue(MyCustomControlProperty, value); }
}
这是我的XAML -
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MyWPF"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="MyWPF.MainWindow"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:CustomClass x:Key="MDP"/>
<local:CustomProperty x:Key="CP"/>
</Window.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<local:MyControl x:Name="btn1" SourceC="abc" Click="MyControl_Click" Width="50" Height="30" RenderTransformOrigin="3.74,4.333" VerticalAlignment="Top" Grid.Row="1" Margin="88.5,67,0,0" HorizontalAlignment="Left" Grid.Column="1" d:LayoutOverrides="Width, Height"/>
</Grid>
我希望看到像“abc”这样的Button Content,如何使用依赖属性创建按钮内容?
答案 0 :(得分:0)
试试这个
public class MyControl : Button
{
public static DependencyProperty MyTextBlockProperty = DependencyProperty.Register("MyTextBlock", typeof(TextBlock), typeof(MyControl), new FrameworkPropertyMetadata(new PropertyChangedCallback(MyTextBlock_Changed)));
public TextBlock MyTextBlock
{
get { return (TextBlock)GetValue(MyTextBlockProperty); }
set { SetValue(MyTextBlockProperty, value); }
}
private static void MyTextBlock_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
MyControl thisClass = (MyControl)o;
thisClass.SetMyTextBlock();
}
private void SetMyTextBlock()
{
//Put Instance MyTextBlock Property Changed code here
}
public static DependencyProperty SourceCProperty = DependencyProperty.Register("SourceC", typeof(string), typeof(MyControl), new FrameworkPropertyMetadata(new PropertyChangedCallback(SourceC_Changed)));
public string SourceC
{
get { return (string)GetValue(SourceCProperty); }
set { SetValue(SourceCProperty, value); }
}
private static void SourceC_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
MyControl thisClass = (MyControl)o;
thisClass.SetSourceC();
}
private void SetSourceC()
{
MyTextBlock.Text = SourceC;
}
public MyControl(): base()
{
MyTextBlock = new TextBlock();
this.Content = MyTextBlock;
}
}