2017-06-20 23 views
0

我有一個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?

回答

1

你可以在你的用戶控件聲明依賴屬性是這樣的:

public static readonly DependencyProperty StartAngleX1Property = 
    DependencyProperty.Register(
     "StartAngleX1", 
     typeof(double), 
     typeof(MyUserControl), 
     new PropertyMetadata(0.0)); 

public double StartAngleX1 
{ 
    get { return (double)GetValue(StartAngleX1Property); } 
    set { SetValue(StartAngleX1Property, value); } 
} 

,並綁定到它在用戶控件的XAML這樣的:

<UserControl ... x:Name="self"> 
    ... 
    <Line X1="{Binding StartAngleX1, ElementName=self}" .../> 
    ... 
</UserControl> 

那麼就沒有必要有一個私人在UserControl中查看模型。你會,而不是綁定用戶控件的屬性,當你使用它,就像

<mycontrol:MyUserControl StartAngleX1="{Binding SomeViewModelPropery}" ... /> 
+0

我看,這是一個方法可行,但不使用ViewModelClass以減少xaml.cs的代碼量的原因是什麼? –

+2

爲什麼你應該有一個視圖模型有很多原因。但是,UserControl不應該有它自己的私有視圖模型實例。相反,它應該在通過DataContext屬性從其環境中繼承的視圖模型上進行操作,例如,從父控件或頁面或窗口。 – Clemens

+0

您當然可以在UserControl的代碼後面進行一些登錄。例如。 StartAngle屬性也可能是UserControl的依賴項屬性,並且控件可能會對PropertyChangedCallback中的值更改作出響應(由PropertyMetadata傳遞)。然後它可以更新其他屬性的值。 – Clemens

相關問題