自定义一个简单控件,添加依赖属性,想在xmal中绑定设置依赖属性的值,绑定不起作用求问是怎么回事?
public partial class LabelEx : UserControl
{
public LabelEx()
{
InitializeComponent();
Data = "000";
this.DataContext = this;
}
public static readonly DependencyProperty DataProperty = DependencyProperty.Register(
"Data", typeof(string), typeof(LabelEx), new FrameworkPropertyMetadata(""));
public string Data
{
get { return (string)GetValue(DataProperty);}
set { SetValue(DataProperty, value);}
}
public string Title
{
get { return title.Text; }
set { title.Text = value; }
}
}
如果将控件属性绑定到Data上能正常工作,如下代码:
<src:LabelEx Data="{Binding Text, ElementName=txt}"></src:LabelEx>
但是我想绑定到对象属性上就不能正常工作,绑定不起作用,前台xmal代码:
<src:LabelEx Data="{Binding XName}"></src:LabelEx>
后台CS代码
```public partial class Window1 : Window, INotifyPropertyChanged
{
private float? age;
public float? Age
{
get { return age; }
set { age = value; NotifyPropertyChanged("Age"); }
}
private float? score;
public float? Score
{
get { return score; }
set { score = value; NotifyPropertyChanged("Score"); }
}
private string xname;
public string XName
{
get { return xname; }
set { xname = value; NotifyPropertyChanged("XName"); }
}
public Window1()
{
InitializeComponent();
this.DataContext = this;
xname = "1234";
age = 60;
score = 380;
}