【问题标题】:Bind a property to another property in C#在 C# 中将一个属性绑定到另一个属性
【发布时间】:2017-09-12 08:57:52
【问题描述】:

我有一个名为Grid 的类,它由另外两个类CircleLine 组成。

public class Grid
{
    public Circle Circle {get; set;}
    public Line Line {get; set;}
}

我希望Line 的几何结构与Circle 的几何结构保持连接。这意味着当我拖动或移动Circle 时。我希望以某种方式通知Line 并根据Circle 的新位置更新其几何形状。

当然,我总是可以使用 CircleLine 的更新几何创建一个新的 Grid,但我不想创建一个新的 Grid。我只是想以某种方式将Line 的端点绑定到例如Circle 的中心。

C# 中的哪些技术允许我这样做?代表? inotifypropertychanged?

【问题讨论】:

  • 您已用inotifypropertychanged 标记您的问题这一事实意味着您已经知道问题的答案。阅读将鼠标悬停在标签上时获得的鼠标悬停文本。
  • @Flater 我不敢说实话。在这种情况下我不知道如何实现它。
  • 好吧,尝试实施它,如果遇到任何问题,请联系我们。 StackOverflow 不是代码编写服务。 Here's an official MSDN example。您也可以使用 google 查找分步教程。
  • @Flater 你误导了我原来的问题。问题不在于如何通过 inotifypropertychanged 实现它。它是关于 C# 中存在哪些技术来以正确的方式实现这一目标。
  • “这是关于 C# 中存在哪些技术来以正确的方式实现这一目标” 答案是 INotifyPropertyChanged。如何通过阅读标签的鼠标悬停文本来回答这个问题? “INotifyPropertyChanged 是在 Microsoft .NET 中定义的一个接口,用于通知侦听器对对象的数据更改。这些通知使数据绑定 UI 控件能够在它们绑定的数据属性发生更改时自动更新其显示。”

标签: c# data-binding properties delegates inotifypropertychanged


【解决方案1】:
public class Circle : INotifyPropertyChanged
{
    private int radius;       
    public int Radius 
    {
        get { return radius; }
        set 
        {
            radius = value;
            RaisePropertyChanged("Radius");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        var propChange = PropertyChanged;
        if (propChange == null) return;
        propChange(this, new PropertyChangedEventArgs(propertyName));
    }
}

然后在 Grid.cs 中

public class Grid
{
    private Circle circle;
    public Circle Circle 
    {
       get { return circle; }
       set 
       {
           circle = value;
           if (circle != null) 
              circle.PropertyChanged += OnPropertyChanged;
       }
    }

    private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == "Radius")
            // Do something to Line
    }
}

【讨论】:

  • 请注意,这仅在您将Circle(或Line)设置为圆(或线)的新实例时才有效。如果更改了现有圆(或线)的属性,则不会。
猜你喜欢
  • 2010-11-14
  • 2018-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多