【问题标题】:Binding inside UserControl在 UserControl 内绑定
【发布时间】:2015-12-15 21:14:06
【问题描述】:

我创建了一个自定义用户控件。在blog post 之后,我的控制代码隐藏如下所示:

public BasicGeoposition PinGeoposition
{
    get { return (BasicGeoposition) GetValue(PropertyPinGeoposition); }
    set { SetValueDp(PropertyPinGeoposition, value);}
}

public static readonly DependencyProperty PropertyPinGeoposition = 
    DependencyProperty.Register("PinGeoposition", typeof(BasicGeoposition), typeof(CustomMapControl), null);

public event PropertyChangedEventHandler PropertyChanged;
void SetValueDp(DependencyProperty property, object value, [System.Runtime.CompilerServices.CallerMemberName] String p = null)
{
    ViewModel.SetMode(ECustomMapControlMode.Default);
    SetValue(property, value);
    if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs(p));
}

使用我的控制:

<customControls:CustomMapControl Mode="ForImage" PinGeoposition="{Binding Geoposition, Mode=TwoWay}" Grid.Row="1"/>

最后在我使用控件的页面的 ViewModel 中:

public BasicGeoposition Geoposition
{
    get { return _geoposition; }
    set
    {
        if (Set(ref _geoposition, value))
        {
            RaisePropertyChanged(() => Geoposition);
        }
    }
}

我希望 ViewModel 中 Geoposition 的每一次变化都会反映在 SetValueDp 中。不幸的是,它不起作用。

【问题讨论】:

    标签: c# xaml user-controls winrt-xaml uwp


    【解决方案1】:

    不确定 Jerry Nixon 在他的博客文章中试图做什么,因为他没有在任何地方分配他的 SetValueDp 方法。

    如果你想调用它,你可以这样做:

    public static readonly DependencyProperty PropertyPinGeoposition = 
    DependencyProperty.Register("PinGeoposition", typeof(BasicGeoposition), typeof(CustomMapControl), new PropertyMetadata(null, SetPosition));
    
    public BasicGeoposition PinGeoposition 
    { 
        get { return (BasicGeoposition) GetValue(PropertyPinGeoposition); } 
        set { SetValue(PropertyPinGeoposition, value);}
    }
    
    private static void SetPosition(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        var control = (CustomMapControl)sender;
    
        var position = e.NewValue as BasicGeoposition;
    
        // Do whatever
    }
    

    编辑:在阅读和重新阅读博客文章之后,我想我把它弄反了(你可能也是这样)。根据我现在的理解,SetValueDp 是一个辅助方法,每当您想更改依赖属性的值时,您都应该调用它。这不是自动调用的。因此,如果您想要一个在修改 DP 时调用的方法,请查看我的解决方案。

    【讨论】:

      猜你喜欢
      • 2013-10-07
      • 1970-01-01
      • 2011-05-22
      • 2020-09-14
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-05
      相关资源
      最近更新 更多