Reputation: 9985
I have a small question but have been finding quite a few different, and mostly ambiguous, answers:
I have the following user control and I am trying to bind to a public property within that control (Events). Everyone says that I have to use the data context, however, I don't really want to do that... I just want to bind to the property from within the control's XAML...
The requirement is that the binding has to be 2 way so any changes in the ui will be reflected in the property (or rather the collection) it is bound to. Each Event object within that collection also implements INotifyPropertyChanged the same way as this control...
Any ideas would be greatly appreciated!
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);
}
}
}
Thanks, Bleepzter.
Upvotes: 3
Views: 1005
Reputation: 50672
You could use a RelativeSource so you don't need the DataContext:
{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type EventEditorWindow }}, Path=Events}
I use this cheat sheet from time to time.
EDIT Oops this is WPF syntax. See this post to have a look at this post to solve it in Silverlight
Upvotes: 1
Reputation: 28016
In the constructor, set DataContext = this. That will effectively make your code behind your DataContext. AFAIK, you can't completely avoid making something the DataContext.
Upvotes: 2