我有一个UserControl绘制一些行,其中坐标(X1,X2,Y1,Y2)绑定到ViewModelClass中的属性,ViewModelClass本身处理要绘制的数学UserControl的行和CodeBehind,您可以在ViewModelClass中设置需要绘制线条的属性的值。下面的代码说明我的控制,它是如何工作的:DependencyProperty在ViewModelClass(UWP)中更改值
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");
}
我怎么能设置DependencyProperties(例如,在UserControl.xaml.cs中显示的StartAngleProperty,而不是StartAngle) UserControl.xaml.cs并仍然使它们更改ViewModelClass中的属性?或者更好地将它们放在CodeBehind中并将ViewModelClass中的属性更改为DependencyProperties?
我看,这是一个方法可行,但不使用ViewModelClass以减少xaml.cs的代码量的原因是什么? –
为什么你应该有一个视图模型有很多原因。但是,UserControl不应该有它自己的私有视图模型实例。相反,它应该在通过DataContext属性从其环境中继承的视图模型上进行操作,例如,从父控件或页面或窗口。 – Clemens
您当然可以在UserControl的代码后面进行一些登录。例如。 StartAngle属性也可能是UserControl的依赖项属性,并且控件可能会对PropertyChangedCallback中的值更改作出响应(由PropertyMetadata传递)。然后它可以更新其他属性的值。 – Clemens