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

标签 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; }
    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)属性 isAnOptionLocation对应图标画笔颜色的画笔颜色。换句话说,当属性 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/

相关文章:

c# - 如何禁用我的 ASP.NET 应用程序的某些 API

c# - 返回 IDisposable 对象后会发生什么情况?

c# - FormView ItemTemplate 中的 ASP.net 访问控制

c# - 从没有反射器/ilspy 的 c# 生成 MSIL 代码

Grails jar依赖重复的log4j绑定(bind)

c# - 我可以要求 child 初始化在其父类中声明的变量吗?

c - C中使用Malloc正确分配二维数组

c++ - Znwm和ZdlPv在汇编中是什么意思?

c# - MVVM 从 View 读取数据到模型

c# - 将组合框绑定(bind)到 wpf 中的另一个组合框