繁体   English   中英

Silverlight CustomControl依赖项属性无法绑定到父视图模型

[英]Silverlight CustomControl dependency property can't be bound to parent viewmodel

我有一个具有依赖项属性的自定义控件

    public static readonly DependencyProperty SelectedUserCodeProperty = DependencyProperty.Register(
    "SelectedUserCode",                               
    typeof(decimal),                           
    typeof(SystemUsersControl),             
    new PropertyMetadata(SelectedUserCodeChanged));
public decimal SelectedUserCode
    {
        get
        {
            return (decimal)this.GetValue(SelectedUserCodeProperty);
        }
        set
        {
            this.SetValue(SelectedUserCodeProperty, value);
            RaisePropertyChanged("SelectedUserCode");
        }
    }

这个控件在另一个用户控件中,我正在尝试在其视图模型中获取上面的依赖项属性,此xaml在父控件中

<SystemUsers:SystemUsersControl Name="ctrlSystemUsersControl" SelectedUserCode="{Binding SelectedSystemUserCode, Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,2,0,0"/>

但没有任何内容绑定到父控件的视图模型

我不知道这是什么问题,这是我第一次处理依赖项属性,我正在考虑将两个控件合为一个:(除非得到任何帮助:)

不用担心

SelectedSystemUserCode必须是一个属性。 如果它是一个属性,则将看到初始值,但将完全支持为您的类绑定的是INotifyPropertyChanged的实现。 这个基本的界面将成为我们的使者。

1)当实现INotifyPropertyChanged时,以下事件将添加到您的类中。

  public event PropertyChangedEventHandler PropertyChanged;

2)然后创建一种射击方法

 public void FirePropertyChanged(string prop)
 {
     if(PropertyChanged!=null)
     {
       PropertyChanged(prop);
      }
  }

3)注册此事件以获取空引用。

  in constructor this.PropertyChanged(s,a)=>{ //may do nothing };

4)//您可以使用Lazy <T>代替它。

  public decimal SelectedSystemUserCode
 {
    get{
          if(_selectedSystemUserCode==null)
              {
                      _selectedSystemUserCode=default(decimal);
              }
        return _selectedSystemUserCode;
      }
    set
      {
     _selectedSystemUserCode=value;
      FirePropertyChanged("SelectedSystemUserCode"); 
      //This will be messanger for our binding
      }
   }

另外,我记得它是默认值,因此您可以为此指定一个十进制值,SelectedUserCodeChanged是回调方法也可以。

 //new PropertyMetadata(SelectedUserCodeChanged) 
 new PropertyMetadata(0) or null

希望会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM