2016-02-16 84 views
0

我想畫一個Bezier曲線,並約束其所有值:綁定多個屬性?

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

因此,在所有情況下,「點」或StartPoint可以被定義我想它獨立綁定到值的一類。

有沒有辦法比手動綁定每個屬性更有效地做到這一點?

回答

-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> 

注意,上面有它轉換PathPointSystem.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; 

現在完成了。