绑定索引属性UserControl

时间:2015-11-22 08:05:47

标签: c# wpf

我创建了UserControl。

<p style="color: white;margin-top:0px">
        CONNECT-U
    </p>

XAML:

public partial class Line : UserControl, INotifyPropertyChanged 
{
    ObservableCollection < Point > points = new ObservableCollection< Point >();

    public static readonly DependencyProperty SpeciesPropertyPoints = DependencyProperty.Register("Points", typeof(ObservableCollection<Point>),
                         typeof(Line), null);

    public ObservableCollection<PointPath> Points
    {
        get { return (ObservableCollection<Point>)GetValue(SpeciesPropertyPoints); }
        set
        {
            SetValue(SpeciesPropertyPoints, (ObservableCollection<Point>)value);
            NotifyPropertyChanged("Points");
        }
    }

    private void Button_Click(object sender, RoutedEventArgs e)

    {
        var point = new Point(100, 50);
        points.Add(point);
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(string propertyName)

    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}


public class Point: INotifyPropertyChanged
{

   private double _x;
    public double X
    {
        get { return _x; }
        set { _x = value; }
    }

    private double _y;
    public double Y
    {
        get { return _y; }
        set { _y = value; }
    }

    public Point()
    {
        X = 0;
        Y = 0;
    }

    public Point(double x, double y)
    {
        X = x;
        Y = y;
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

我希望在点击TexBox中的按钮后输入名称&#34; x&#34;显示点[0] .X(即100)和TexBox中的名称&#34; y&#34;显示点[0] .Y(即50)。请帮我理解。

1 个答案:

答案 0 :(得分:1)

您应该更改文字装订:

TextBox x:Name="x" Width="20" Text="{Binding Path=Points[0].X}" 
TextBox x:Name="y" Width="20" Text="{Binding Path=Points[0].Y}"

你的DP实施错了, 应该是这样的

public static readonly DependencyProperty PointsProperty = DependencyProperty.Register(
        "Points", typeof (ObservableCollection<Point>), typeof (Line), new PropertyMetadata(default(ObservableCollection<Point>)));

    public ObservableCollection<Point> Points
    {
        get { return (ObservableCollection<Point>) GetValue(PointsProperty); }
        set { SetValue(PointsProperty, value); }
    }

你不应该在DP setter中编写逻辑,因为它只是CLR Property包装器,并且不能保证在某些情况下会调用setter!

编辑: enter image description here