如何将对象绑定到动态创建的标签?

时间:2014-11-29 19:47:35

标签: c#

我正在尝试绑定,但它似乎不起作用:/

我的代码:

    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");
        }
    }

但我不知道我在做什么。

1 个答案:

答案 0 :(得分:0)

您的绑定应该可以正常工作,但如果您希望更改Magnitude属性以自动显示在您的视图中,那么您必须让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");
        }
    }
}