Routed events and Dependency propetries - wpf

I have a user control with a dependency property. When that property is changed, I want to cascade a RoutedEvent up to the main application and execute some function. Here is my user control code:
public TCardBase SelectedTCard
{
get { return (TCardBase)GetValue(SelectedTCardProperty); }
set { SetValue(SelectedTCardProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedTCard. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedTCardProperty =
DependencyProperty.Register("SelectedTCard", typeof(TCardBase), typeof(TCardView), new PropertyMetadata(SelectedTCardPropertyChanged));
private static void SelectedTCardPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
//SEND EVENT HERE TO MAIN APPLICATION
}
What is the best way to send this event to the main application? Thanks.

There are plenty of nice examples online how to create custom routed events.
Take a look at this code:
// This event uses the bubbling routing strategy
public static readonly RoutedEvent TapEvent = EventManager.RegisterRoutedEvent(
"Tap", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TCardView));
// Provide CLR accessors for the event
public event RoutedEventHandler Tap
{
add { AddHandler(TapEvent, value); }
remove { RemoveHandler(TapEvent, value); }
}
// This method raises the Tap event
void RaiseTapEvent()
{
RoutedEventArgs newEventArgs = new RoutedEventArgs(TCardView.TapEvent);
RaiseEvent(newEventArgs);
}
public TCardBase SelectedTCard
{
get { return (TCardBase)GetValue(SelectedTCardProperty); }
set { SetValue(SelectedTCardProperty, value); }
}
// Using a DependencyProperty as the backing store for SelectedTCard. This enables animation, styling, binding, etc...
public static readonly DependencyProperty SelectedTCardProperty =
DependencyProperty.Register("SelectedTCard", typeof(TCardBase), typeof(TCardView), new PropertyMetadata(SelectedTCardPropertyChanged));
private static void SelectedTCardPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
((TCardView)o).RaiseTapEvent();
}
Try it out. :)

Related

Dependent DependencyProperty

I want to make a dependency property whose value depend on other dependency property but still settable/writable. For example, ‘DateOfBirth’ is an independent DependencyProperty. Now I want to make another DependencyProperty with name YearOfBirth. When DateOfBirth with Change it will Coerce the value of YearOfBirth property. i.e. d.CoerceValue(YearOfBirthProperty).
But How can I make dependent dependency property (e.g. YearOfBirth) writeable/settable?
If I code using CLR Properties, it works fine but how can do by using Dependency Properties!
What about this:
public partial class MainWindow : Window
{
public static DependencyProperty DateofBirthProperty = DependencyProperty.Register("DateofBirth", typeof(DateTime), typeof(MainWindow), new FrameworkPropertyMetadata(new PropertyChangedCallback(DateofBirth_Changed)));
public DateTime DateofBirth
{
get { return (DateTime)GetValue(DateofBirthProperty); }
set { SetValue(DateofBirthProperty, value); }
}
private static void DateofBirth_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
MainWindow thisClass = (MainWindow)o;
thisClass.SetDateofBirth();
}
private void SetDateofBirth()
{
DOBYear = DateofBirth.Year;
}
public static DependencyProperty DOBYearProperty = DependencyProperty.Register("DOBYear", typeof(int), typeof(MainWindow), new FrameworkPropertyMetadata(new PropertyChangedCallback(DOBYear_Changed)));
public int DOBYear
{
get { return (int)GetValue(DOBYearProperty); }
set { SetValue(DOBYearProperty, value); }
}
private static void DOBYear_Changed(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
MainWindow thisClass = (MainWindow)o;
thisClass.SetDOBYear();
}
private void SetDOBYear()
{
//Put Instance DOBYear Property Changed code here
}
public MainWindow()
{
InitializeComponent();
}
}

Scenario with dependency properties-how to access each other

I have a two dependency properties(both List of strings) in a custom user control.The binding for one of these dependency properties can be changed several times for the life of the application. I need to do some action in the user control when the binding is changed, and I need to access all the dependency properties in the class for doing the action.
For example,
public class UC:UserControl
{
public List<string> AvailableItems
{
get { return (List<string>)this.GetValue(AvailableItemsProperty); }
set { this.SetValue(AvailableItemsProperty, value); }
}
public static readonly DependencyProperty AvailableItemsProperty = DependencyProperty.Register(
"AvailableItems", typeof(List<string>), typeof(ItemSelectionUserControl), new FrameworkPropertyMetadata(OnAvailableItemsChanged) { BindsTwoWayByDefault = true });
public List<string> SelectedItems
{
get { return (List<string>)this.GetValue(SelectedItemsProperty); }
set { this.SetValue(SelectedItemsProperty, value); }
}
public static readonly DependencyProperty SelectedItemsProperty = DependencyProperty.Register(
"SelectedItems", typeof(List<string>), typeof(ItemSelectionUserControl), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true });
public static void OnAvailableItemsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
//How to access SelectedItems here??
}
}
The trouble is the the callback when dependency property changed should be static, so how can I access the non static dependency property wrapper in the function?? Or is there any other way to do this??
Use the following:
public static void OnAvailableItemsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
UC uc = sender as UC;
List<string> selectedItems = uc.SelectedItems;
}

ObservableCollection has Depedency Property in Silverlight

Recently i was developing a custom control in Silverlight, I created custom dependency property which is of type ObservableCollection. I have another 2 custom dependency properties of type strings. My requirement is on addition of any item to collection, I have to fire collectionChanged Event , in this event handler, i want to update the other 2 dependency properties.
public static readonly DependencyProperty itemsProperty = DependencyProperty.Register("Items", typeof(ObservableCollection<ValidationErrorMessage>), typeof(SummaryUserControl), new PropertyMetadata(new ObservableCollection<ValidationErrorMessage>(), new PropertyChangedCallback(fun1)));
public ObservableCollection<ValidationErrorMessage> Items
{
get
{
return (ObservableCollection<ValidationErrorMessage>)base.GetValue(itemsProperty);
}
set
{
base.SetValue(itemsProperty, value);
}
}
public static void fun1(object sender, DependencyPropertyChangedEventArgs evt)
{
var newValue = evt.NewValue as ObservableCollection<ValidationErrorMessage>;
if(newValue!=null)
newValue.CollectionChanged += new NotifyCollectionChangedEventHandler(CollectionChangedHandler);
var oldValue = evt.OldValue as ObservableCollection<ValidationErrorMessage>;
if(oldValue!=null)
oldValue.CollectionChanged -= new NotifyCollectionChangedEventHandler(CollectionChangedHandler);
}
static void CollectionChangedHandler(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
var newItems = e.NewItems as ObservableCollection<ValidationErrorMessage>;
foreach (var item in newItems)
{
item.PropertyChanged += new PropertyChangedEventHandler(item_PropertyChanged);
}
}
}
static void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
}
public static readonly DependencyProperty headerProperty = DependencyProperty.Register("Header", typeof(String), typeof(SummaryUserControl), new PropertyMetadata(String.Empty, null));
public String Header
{
get
{
return (String)base.GetValue(headerProperty);
}
set
{
base.SetValue(headerProperty, value);
RaisePropertyChange("Header");
}
}
public static readonly DependencyProperty messageTypeProperty =
DependencyProperty.Register("MessageType", typeof(MessageEnumType), typeof(SummaryUserControl), new PropertyMetadata(MessageEnumType.Error, null));
public MessageEnumType MessageType
{
get { return (MessageEnumType)GetValue(messageTypeProperty); }
set { SetValue(messageTypeProperty, value); RaisePropertyChange("MessageType"); }
}
How can I change the values of the dependency properties messageType and Header? I'm unable to access those properties in either the CollectionChanged or NotifyPropertyChanged event since all those events are static. I cannot access the instance within these static event handlers.
I tried to fix the problem with a converter, but my curosity on Silverlight makes me want to use the above approach. How can I set values for those dependency properties within CollectionChanged event or NotifyPropertyChanged events?
The sender in your static fun1 method should be the instance of the class which declares the itemsProperty DependencyProperty. Therefore you can access the concrete instance with casting the sender to your class.
public static void fun1(object sender, DependencyPropertyChangedEventArgs evt)
{
MyClass concreteInstance = sender as MyClass;
if(concreateInstance != null)
{
[...your code...]
}
}

How do I create a public event for a dependency property?

In the code below you can see what I'm trying to do, but it doesn't work. I want an event that I can attach to outside of my user control and fires whenever the dependency property changes.
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value"
, typeof(Double)
, typeof(ucSlider)
, new PropertyMetadata(50d, new PropertyChangedCallback(OnValueChanged)));
public Double Value
{
get { return (Double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public event PropertyChangedCallback OnValueChanged;
Dependency properties are static, but your event is related with the instance of the class. So you need an intermediate method between the static property and the event of instance.
In this example I pass the static method OnValuePropertyChanged as a callback parameter and inside it I raise the event:
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value"
, typeof(Double)
, typeof(ucSlider)
, new PropertyMetadata(50d, new PropertyChangedCallback(OnValuePropertyChanged)));
public Double Value
{
get { return (Double)GetValue(ValueProperty); }
set { SetValue(ValueProperty, value); }
}
public static void OnValuePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var sl = sender as ucSlider;
if (sl != null)
sl.RaiseValueChangedEvent(e);
}
private void RaiseValueChangedEvent(DependencyPropertyChangedEventArgs e)
{
if(this.OnValueChanged != null)
this.OnValueChanged(this, e);
}
public event PropertyChangedCallback OnValueChanged;

Silverlight Dependancy Property Change Event Problem

I have a custom control that has a Dependancy Property...it has a few but let us say Dragable is my problem. The property is a boolean and I want to execute a piece of code each time it changes...a toggle.
I have two options, both shown below
[Category("Modal Options")]
public bool Dragable
{
get { return (bool)GetValue(DragableProperty); }
set { SetValue(DragableProperty, value); toggleDragable(); }
}
// Using a DependencyProperty as the backing store for Dragable. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DragableProperty =
DependencyProperty.Register("Dragable", typeof(bool),
typeof(PlussWindow), new PropertyMetadata(false));
private void MakeDragable()
{
this.dragBehavior.Attach(this.LayoutRoot);
}
private void MakeUnDragable()
{
this.dragBehavior.Detach();
}
public virtual void toggleDragable()
{
if (this.Dragable)
{
MakeUnDragable();
}
else
{
MakeDragable();
}
}
or
[Category("Modal Options")]
public bool Dragable
{
get { return (bool)GetValue(DragableProperty); }
set { SetValue(DragableProperty, value); }
}
// Using a DependencyProperty as the backing store for Dragable. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DragableProperty =
DependencyProperty.Register("Dragable", typeof(bool),
typeof(PlussWindow), new PropertyMetadata(false, (o, e) => { (o as PlussWindow).toggleDragable(); }
));
private void MakeDragable()
{
this.dragBehavior.Attach(this.LayoutRoot);
}
private void MakeUnDragable()
{
this.dragBehavior.Detach();
}
public virtual void toggleDragable()
{
if (this.Dragable)
{
MakeUnDragable();
}
else
{
MakeDragable();
}
}
Each method results in a 'Object reference not set to an instance of an object'
I usually use binding to get over this problem, e.g Visibility or Text are easily done, but for custom functionality I need to enable this in code.
How do I do this, noting that the propertychanged method is static?
Try this:
public bool Dragable
{
get { return (bool)GetValue(DragableProperty); }
set { SetValue(DragableProperty, value); }
}
public static readonly DependencyProperty DragableProperty =
DependencyProperty.Register("Dragable", typeof(bool), typeof(PlussWindow), new PropertyMetadata(false, new PropertyChangedCallback(onDragableChange)));
private static void onDragableChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
bool validate = (bool)e.NewValue;
PlussWindow win = (PlussWindow) d;
if (validate)
{
win.dragBehavior.Attach(this.LayoutRoot);
}
else
{
win.dragBehavior.Detach();
}
}

Resources