这个问题完全涉及代码,不涉及 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
方法。
现在,在 MainWindow(它是一个 WPF 项目)中,我声明 List<Location> locations
并用数据填充它。
有时我将“图标”放在现有的 GridScroller
上像这样:
gridScroller.Children.Add(location.createIcon());
现在,我遇到的问题是我想绑定(bind)属性 isAnOption
的 Location
对应图标画笔颜色的画笔颜色。换句话说,当属性 isAnOption
来自 Location
的某个对象已更改,我希望该更改反射(reflect)在 GridScroller 上的椭圆的颜色中。
请帮忙。
谢谢
最佳答案
首先,您的 Location 类需要 implement INotifyPropertyChanged ,因此任何使用 isAnOption
作为源的绑定(bind)都将在更改时收到通知。
然后您可以像这样将 Fill 属性绑定(bind)到您的属性:
Binding binding = new Binding("isAnOption") {
Source = this,
Converter = new MyConverter(),
};
icon.SetBinding(Ellipse.FillProperty, binding);
最后,MyConverter 将是一个自定义 IValueConverter根据传递的 bool 值返回蓝色或红色画笔。
关于c# 将类属性绑定(bind)到复杂结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6509855/