[英]Binding on Indexed properties UserControl
我創建了用戶控件。
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));
}
}
}
XAML:
Button Click="Button_Click"
TextBox x:Name="x" Width="20" Text="{Binding Points[0].X}"
TextBox x:Name="y" Width="20" Text="{Binding Points[0].Y}"
我想在 TexBox 中單擊名稱為“x”的按鈕顯示 Points[0].X(即 100)並在 TexBox 中單擊名稱為“y”的按鈕顯示 Points[0].Y(即 50)。 請幫我理解。
您應該更改文本綁定:
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 屬性包裝器,並且不能保證在某些情況下會調用 setter!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.