【问题标题】:Binding multiple properties?绑定多个属性?
【发布时间】:2016-02-16 06:48:48
【问题描述】:

我正在尝试绘制贝塞尔曲线并绑定其所有值:

<PathFigure StartPoint="20,20" IsClosed="False">
     <BezierSegment Point1="70,130" Point2="220,20" Point3="180,160"/>
</PathFigure>

所以在所有情况下都定义了“Point”或 StartPoint,我希望将其独立绑定到类中的值。

有没有比手动绑定每个属性更有效的方法?

【问题讨论】:

    标签: c# wpf xaml properties


    【解决方案1】:

    对于这个特定的问题,您可以执行以下操作:

    基本上我们仍在使用 MVVM 模式。首先你需要PathPoint 类和PathFigureViewModel 类来代表你的数据。

    public class PathPoint
    {
        public int X
        {
            get;
            set;
        }
    
        public int Y
        {
            get;
            set;
        }
    }
    

    public class PathFigureViewModel
    {
        public PathPoint StartPoint
        {
            get; set;
        }
    
        public PathPoint Point1
        {
            get; set;
        }
    
        public PathPoint Point2
        {
            get; set;
        }
    
        public PathPoint Point3
        {
            get; set;
        }
    
    }
    

    然后你可以定义你的PathFigure 如下:

    <PathFigure x:Name="PathFigure1" StartPoint="{Binding StartPoint, Converter={StaticResource PointConvertor}}" IsClosed="False">
         <BezierSegment Point1="{Binding Point1, Converter={StaticResource PointConvertor}}" Point2="{Binding Point2, Converter={StaticResource PointConvertor}}" Point3="{Binding Point3, Converter={StaticResource PointConvertor}}"/>
    </PathFigure>
    

    请注意,上面有一个转换器将PathPoint 转换为System.Windows.Point,如下所示:

    public class PointToPathPointConvertor : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var p = value as PathPoint;
            return new System.Windows.Point(p.X, p.Y);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
    

    最后你需要设置DataContext。由于PathFigure 不公开DataContext 属性,您可以设置其父Path 对象的DataContext 属性。类似于以下内容:

    PathFigureViewModel vm = new PathFigureViewModel();
    vm.StartPoint = new PathPoint() { X = 20, Y = 20 };
    vm.Point1 = new PathPoint() { X = 70, Y = 130 };
    vm.Point2 = new PathPoint() { X = 220, Y = 20 };
    vm.Point3 = new PathPoint() { X = 180, Y = 160 };
    
    this.Path.DataContext = vm;
    

    现在已经完成了。

    【讨论】:

      猜你喜欢
      • 2011-04-28
      • 2023-03-21
      • 1970-01-01
      • 2010-12-05
      • 2019-05-18
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多