c#将类属性绑定到复杂结构

c#将类属性绑定到复杂结构,c#,dynamic,binding,C#,Dynamic,Binding,这个问题完全涉及代码,没有XAML 所以我有一个类,叫做Location: public class Location { public int id { get; set; } public double latitude { get; set; } public double longitude { get; set; } public string name { get; set; } public string type { get; set; }

这个问题完全涉及代码,没有XAML

所以我有一个类,叫做
Location

public class Location
{
    public int id { get; set; }
    public double latitude { get; set; }
    public double longitude { get; set; }
    public string name { get; set; }
    public string type { get; set; }
    public bool isAnOption { get; set; }

    public Location(int newId, double newLatitude, double newLongitude, string newName, string newType)
    {
        id = newId;
        latitude = newLatitude;
        longitude = newLongitude;
        name = newName;
        type = newType;
        isAnOption = true;
    }

    public System.Windows.Shapes.Ellipse createIcon()
    {
        System.Windows.Shapes.Ellipse icon = new System.Windows.Shapes.Ellipse();
        SolidColorBrush brush;
        if (isAnOption)
        {
            brush = new SolidColorBrush(Colors.Blue);
        }
        else
        {
            brush = new SolidColorBrush(Colors.Red);
        }
        brush.Opacity = 0.5;
        icon.Fill = brush;
        icon.Height = icon.Width = 44;
        icon.HorizontalAlignment = HorizontalAlignment.Left;
        icon.VerticalAlignment = VerticalAlignment.Top;

        Thickness locationIconMarginThickness = new Thickness(0, 0, 0, 0);
        locationIconMarginThickness.Left = (longitude - 34.672852) / (35.046387 - 34.672852) * (8704) - 22;
        locationIconMarginThickness.Top = (32.045333 - latitude) / (32.045333 - 31.858897) * (5120) - 22;
        icon.Margin = locationIconMarginThickness;

        Label labelName = new Label();
        labelName.Content = name;

        StackPanel locationData = new StackPanel();
        locationData.Children.Add(labelName);

        ToolTip toolTip = new ToolTip();
        toolTip.Content = locationData;

        icon.ToolTip = toolTip;

        return icon;
    }
}
非常直截了当。注意
createIcon
方法

现在,在主窗口(这是一个WPF项目)中,我声明
列出位置
,并用数据填充它

在某个时刻,我将“图标”放在现有的
GridScroller
上,如下所示:

gridScroller.Children.Add(location.createIcon()); 
现在,我遇到的问题是,我想将
Location
的属性
isAnOption
绑定到相应图标笔刷颜色的笔刷颜色。换句话说,当从
Location
派生的某个对象的属性
isAnOption
发生更改时,我希望该更改反映在GridScroller上的椭圆颜色中。 请帮忙


首先感谢您的Location类需要这样做,因此任何使用
isAnOption
作为源的绑定在发生更改时都会得到通知

然后可以将Fill属性绑定到属性,如下所示:

Binding binding = new Binding("isAnOption") {
    Source = this,
    Converter = new MyConverter(),
};
icon.SetBinding(Ellipse.FillProperty, binding);

最后,MyConverter将是一个自定义程序,根据传递的布尔值返回蓝色或红色笔刷。

Wow!code裸体,这真的很快。请您给我一个建议,在我的代码中实现
INotifyPropertyChanged
IValueConverter
?@zazkapulsk-我提供的两个链接都有代码示例,您可以根据您的情况进行调整。@zazkapulsk-没问题。如果有什么你不理解或需要澄清的具体问题,请随时提问。