我尝试将用户控件创建为:
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); }
}
}
它的xaml是:
<Grid x:Name="LayoutRoot">
<TextBlock x:Name="Title" Text="{Binding Label}" />
<TextBlock x:Name="MyText" Text="{Binding MyText}" TextWrapping="Wrap"/>
</Grid>
我想要的是尝试将此控件中的依赖属性绑定到UI元素,这样当我使用此控件时,我可以设置数据绑定,如:
<local:MyTextBlock Label="{Binding ....}" MyText = "{Binding ....}" />
但是当我按照上面那样做时,它不起作用。没有数据绑定,没有错误。如何解决?
答案 0 :(得分:5)
将它们放在一起
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;
}
}
}
答案 1 :(得分:0)
基本上你只需将这些依赖属性包装在一个类中。将控件上的DataContext
设置为该类的实例并绑定。