C# 如何将对象绑定到动态创建的标签?
我正在尝试绑定,但似乎不起作用:/ 我的代码:C# 如何将对象绑定到动态创建的标签?,c#,C#,我正在尝试绑定,但似乎不起作用:/ 我的代码: void Binding(velocity Object, Label Output, string Field) { Binding newBinding = new Binding(); newBinding.Source = Object; newBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
void Binding(velocity Object, Label Output, string Field)
{
Binding newBinding = new Binding();
newBinding.Source = Object;
newBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
newBinding.Path = new PropertyPath(Field);
Output.SetBinding(Label.ContentProperty, newBinding);
}
Binding(newProjectile.CurrentVelocity, lbl_CurrentVelOutput, "Magnitude"); // how i call it
非常感谢!
编辑:我没有得到错误,只是输出上的标签没有改变
编辑:我试着寻找如何实现INotifyChange接口,得到了如下结果
public class velocity : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler Handler = PropertyChanged;
if (Handler != null)
{
Handler(this, new PropertyChangedEventArgs(name));
}
}
public double Velocity
{
get { return Magnitude; }
set
{
Magnitude = value;
OnPropertyChanged("10");
}
}
但是我不知道我在做什么。您的绑定应该工作得很好,但是如果您希望对magnize属性的更改自动显示在您的视图中,那么您必须让WPF知道这些更改。这就是INotifyProperty接口的用武之地,因为它允许您的代码让WPF知道哪些属性已更改:
// In C#, the common convention is to give classes CamelCased names:
public class Velocity : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
// Local variables and method arguments are also camelCased,
// but they start with a lower-case character:
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
// Properties with default getters and setters automatically get a 'backing field',
// but we can't use that because we need to call OnPropertyChanged, so we'll have to
// manually write out things. Normally, you'd give the backing field a name similar
// to the property, so it's obvious that they belong together:
private double _magnitude;
public double Magnitude
{
get { return _magnitude; }
set
{
_magnitude = value;
// Here, you need to pass in the *name* of the property that's being changed,
// so WPF knows which views it needs to update (WPF can fetch the new value
// by itself):
OnPropertyChanged("Magnitude");
}
}
}
您的标签绑定看起来如何?有没有可能有更多的代码?对象和字段是什么?添加了参数字段字段字段字段或属性的名称?绑定仅适用于属性。在.CurrentVelocity中有一个属性表示幅值。我做得对吗?