DependencyProperty更改ViewModelClass(UWP)中的值

时间:2017-06-20 09:31:45

标签: c# xaml mvvm uwp

我有一个UserControl,它绘制了一些坐标(X1,X2,Y1,Y2)绑定到ViewModelClass中的属性的行,ViewModelClass本身处理绘制行的数学和UserControl的CodeBehind可以设置ViewModelClass中绘制线条所需的属性值。以下代码解释了我的控件及其工作原理:

UserControl.xaml

public Constructor()
{
    private readonly ViewModel model = new ViewModel();
    DataContext = model;
}

public int StartAngle
{
    get { return model.StartAngle; }
    set { model.StartAngle = value; }
}

UserControl.xaml.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");
}

ViewModel.cs

_mm_add_ps(_mm_mul_ps(a, b), c)
_mm_fmadd_ps(a, b, c)

如何在UserControl.xaml.cs中设置DependencyProperties(例如StartAngleProperty而不是UserControl.xaml.cs中显示的StartAngle)并仍然让它们更改ViewModelClass中的Property?或者更好的做法是将它们放在CodeBehind中并将ViewModelClass中的Properties更改为DependencyProperties?

1 个答案:

答案 0 :(得分:1)

您可以在UserControl中声明依赖项属性,如下所示:

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

并在UserControl的XAML中绑定它,如下所示:

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

然后,您的UserControl中不需要私有视图模型。您可以在使用它时绑定UserControl的属性,例如

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED)
    {
        //do not process data, I use return; to resume activity calling camera intent
        enter code here
    }
}