我试图创建一个用户控件:
public partial class MyTextBlock : UserControl
{
public MyTextBlock()
{
InitializeComponent();
}
public static readonly DependencyProperty LabelProperty
= DependencyProperty.RegisterAttached("Label", typeof(string), typeof(MyTextBlock), null);
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
public static readonly DependencyProperty MyTextProperty
= DependencyProperty.RegisterAttached("MyText", typeof(string), typeof(MyTextBlock), null);
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
}
Run Code Online (Sandbox Code Playgroud)
它的xaml是:
<Grid x:Name="LayoutRoot">
<TextBlock x:Name="Title" Text="{Binding Label}" />
<TextBlock x:Name="MyText" Text="{Binding MyText}" TextWrapping="Wrap"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)
想要我想要尝试将此控件中的依赖属性绑定到UI元素,这样当我使用此控件时,我可以设置数据绑定,如:
<local:MyTextBlock Label="{Binding ....}" MyText = "{Binding ....}" />
Run Code Online (Sandbox Code Playgroud)
但是,当我按照上面的方式行事时,它不起作用.没有数据绑定,没有错误.怎么解决?
把它们放在一起
public partial class MyTextBlock : UserControl
{
public MyTextBlock()
{
InitializeComponent();
}
public static readonly DependencyProperty LabelProperty
= DependencyProperty.Register("Label", typeof(string), typeof(MyTextBlock), new PropertyMetadata(new PropertyChangedCallback(LabelChanged)));
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
private static void LabelChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var c = d as MyTextBlock;
if (c != null )
{
c.label.Text = e.NewValue as string;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4463 次 |
| 最近记录: |