2011-05-23 45 views
3

我有一个小问题,但已经找到了不少,不同而且大多含糊不清,答案:如何在不使用DataContext的情况下绑定到Silverlight中的本地属性?

我有以下用户控件,我试图绑定到该控件(事件)内的公共属性。每个人都说我必须使用数据上下文,但是,我并不想这么做......我只想绑定到控件的 XAML内的属性...

要求是绑定必须是2种方式,所以ui中的任何更改都会反映在绑定的属性(或集合)中。该集合中的每个Event对象也以与此控件相同的方式实现INotifyPropertyChanged ...

任何想法都将不胜感激!

public partial class EventEditorWindow : UserControl, INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    public ObservableCollection<Event> events; 
    public ObservableCollection<Event> Events 
    { 
     get { return this.events; } 
     set 
     { 
      if(this.events != value) 
      { 
       this.events = value; 
       this.RaisePropertyChanged("Events"); 
      } 
     } 
    } 

    private void RaisePropertyChanged(string propertyName) 
    { 
     if (PropertyChanged != null) 
     { 
      this.VerifyPropertyName(propertyName); 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    [Conditional("DEBUG")] 
    [DebuggerStepThrough] 
    public void VerifyPropertyName(string propertyName) 
    { 
     var currentObjectType = this.GetType(); 

     if (currentObjectType.GetProperty(propertyName) == null) 
     { 
      throw new ArgumentException("Property not found", propertyName); 
     } 
    } 
} 

谢谢, Bleepzter。

回答

1

在构造函数中,设置DataContext = this。这将有效地使你的代码在你的DataContext后面。 AFAIK,你不能完全避免东西的DataContext。

+0

谢谢!我会马上尝试。当我以编程方式更新集合时,是否也必须添加该行代码? – bleepzter 2011-05-23 20:15:49

+1

否 - 您的PropertyChanged事件将处理该问题 – ColinE 2011-05-23 20:17:04

+1

您不应该,不。另外,如果您只是从集合中添加/删除项目,则无需实施INotifyPropertyChanged。 observableCollection已经负责通知添加/删除/清除。 – 2011-05-23 20:18:46

1

你可以使用的RelativeSource,所以你不需要的DataContext:

{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type EventEditorWindow }}, Path=Events} 

我用this cheat sheet不时。

编辑糟糕,这是WPF语法。看到这个职位看看this post to solve it in Silverlight

+0

谢谢你的这张备忘单。当我试图实现AncestorType = {x:type ...}时,我得到了错误的类“相对资源没有实现AncestorType”...但我发现绑定备忘单非常有用! – bleepzter 2011-05-24 02:25:37

相关问题