【问题标题】:WPF MVVM get UserControl actual position via a DependencyPropertyWPF MVVM 通过 DependencyProperty 获取 UserControl 实际位置
【发布时间】:2015-08-20 20:00:23
【问题描述】:

我有一个非常常见的设计 MVVM 应用程序:MainWindow 有一个 ContentPresenter 定义如下:

    <ContentPresenter Grid.Row="1" Grid.Column="1"
                      Content="{Binding Path=CurrentViewModel}">
    </ContentPresenter>

它使用DataTemplate并且可以切换视图:

    <DataTemplate DataType="{x:Type vm:PlateEntireViewModel}">
        <v:PlateEntireView/>
    </DataTemplate>

PlateEntireView 是一个以 PlateEntireViewModel 作为 DataContext 的用户控件。现在 - 我想在 PlateEntireViewModel 中有一个属性,它将在 MainWindow 内保存 PlateEntireView 的实际位置(左、上)。这可以实现吗?是否可以制作一些 DependencyProperty 并在 PlateEntireView 中使用它,例如:

    <Grid ext:CustomProperties.ActualPositionX="{Binding Path=ActualPositionX, Mode=OneWayToSource}">
    </Grid>

谁能告诉我这是否是正确的尝试方式 - 以及如何使用它?

【问题讨论】:

    标签: wpf mvvm


    【解决方案1】:

    因此,最短的答案通常是 ViewModel 不会关心 View 中显示的特定坐标。话虽这么说,这样做相对简单。

    您需要做的就是设置一个附加属性,该属性将从屏幕的左上角检索点

    public static double GetXCoordinate(DependencyObject obj)
        {
            var fe = obj as FrameworkElement;
            if (fe != null)
            {
                return (fe.PointToScreen(new Point())).X;
            }
            return -1;
        }
    
        public static void SetXCoordinate(DependencyObject obj, double value)
        {
            obj.SetValue(XCoordinateProperty, value);
        }
    
        // Using a DependencyProperty as the backing store for XCoordinate.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty XCoordinateProperty =
            DependencyProperty.RegisterAttached("XCoordinate", typeof(double), typeof(CustomProperties), new PropertyMetadata(0.0));
    

    那么你可以让你的绑定看起来像这样

    <local:control Grid.Column="1"
                       Grid.Row="1" 
                       x:Name="cp"
                       local:CustomProperties.XCoordinate="{Binding XCoordinate, UpdateSourceTrigger=Explicit}"
                       />
    

    但您需要显式更新,因为此绑定永远不会触发任何更改事件。您可以通过在您的视图中挂钩一个合理的事件来做到这一点。有关该外观的更多信息here

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多