【发布时间】:2017-11-22 18:27:06
【问题描述】:
我有一个 UserControl,它绘制了一些线,其中坐标(X1,X2,Y1,Y2)绑定到 ViewModelClass 中的属性,ViewModelClass 本身处理数学以绘制线条,以及您所在的 UserControl 的 CodeBehind可以设置 ViewModelClass 中绘制线条所需的属性的值。以下代码解释了我的 Control 及其工作原理:
UserControl.xaml
<Line x:Name="StartAngleLine" X1="{Binding Path=StartAngleX1}" X2="{Binding Path=StartAngleX2}" Y1="{Binding Path=StartAngleY1}" Y2="{Binding Path=StartAngleY2}" Stroke="Aqua" StrokeThickness="6"/>
UserControl.xaml.cs
public Constructor()
{
private readonly ViewModel model = new ViewModel();
DataContext = model;
}
public int StartAngle
{
get { return model.StartAngle; }
set { model.StartAngle = value; }
}
ViewModel.cs
public int StartAngle
{
get
{
return startAngle;
}
set
{
if (value != startAngle)
{
if (value >= 0 && value <= 360)
{
startAngle = value;
NotifyPropertyChanged();
StartAngleChanged();
}
else
{
throw new ArgumentOutOfRangeException($"StartAngle", "Angle is out of range.");
}
}
}
}
public double StartAngleX1
{
get
{
startAngleX1 = centerX + (centerX1 * Math.Cos(StartAngle * (Math.PI / 180)));
return startAngleX1;
}
}
private void StartAngleChanged()
{
NotifyPropertyChanged("StartAngleX1");
NotifyPropertyChanged("StartAngleX2");
NotifyPropertyChanged("StartAngleY1");
NotifyPropertyChanged("StartAngleY2");
}
如何在我的 UserControl.xaml.cs 中设置 DependencyProperties(例如 StartAngleProperty 而不是如 UserControl.xaml.cs 中所示的 StartAngle)并仍然让它们更改 ViewModelClass 中的属性?还是将它们留在 CodeBehind 中并将 ViewModelClass 中的属性更改为 DependencyProperties 更好?
【问题讨论】: