WPF - GetBindingExpression in PropertyChangedCallback of DependencyProperty - c#

I need to be able to access the binding expression for the Text property of a TextBox from within a DependencyProperty on a TextBox. the value of my DependencyProperty is set in XAML. I'm calling GetBindingExpression in the PropertyChangedCallback method of my DependencyProperty, but I'm too early at this point because GetBindingExpression always returns null here, yet after the window fully loads it definitely returns a value (I tested using a button on screen to change the value of my DependencyProperty).
Clearly I have a load order issue here where my DependencyProperty's value is set before the Text property is bound to my view model. My question is, is there some event I can hook into to identify when the binding of the Text property is complete? Preferably without modifying the XAML of my TextBox as I have hundreds of them in the solution.
public class Foobar
{
public static readonly DependencyProperty TestProperty =
DependencyProperty.RegisterAttached(
"Test", typeof(bool), typeof(Foobar),
new UIPropertyMetadata(false, Foobar.TestChanged));
private static void TestChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
var textBox = (TextBox)o;
var expr = textBox.GetBindingExpression(TextBox.TextProperty);
//expr is always null here, but after the window loads it has a value
}
[AttachedPropertyBrowsableForType(typeof(TextBoxBase))]
public static bool GetTest(DependencyObject obj)
{
return (bool)obj.GetValue(Foobar.TestProperty);
}
[AttachedPropertyBrowsableForType(typeof(TextBoxBase))]
public static void SetTest(DependencyObject obj, bool value)
{
obj.SetValue(Foobar.TestProperty, value);
}
}

Try listen to LayoutUpdated event. I think its called layout updated event. Else google it. Its a crazy little event which will be fired everytime no matter what you do ex. when loading, drawing, even when you move your mouse!
Take a look at this pseudo code:
private static void TestChanged(DependencyObject o, DependencyPropertyChangedEventArgs args)
{
var textBox = (TextBox)o;
// start listening
textBox.LayoutUpdated += SomeMethod();
}
private static void SomeMethod(...)
{
// this will be called very very often
var expr = textBox.GetBindingExpression(TextBox.TextProperty);
if(expr != null)
{
// finally you got the value so stop listening
textBox.LayoutUpdated -= SomeMethod();

Related

Convert to DependencyProperty

I have a question, someone could help transform this code (used in codebehind ) for use by dependyProperty ?
This code gives the focus to the first item of listview . THX!!!!!!
private void ItemContainerGeneratorOnStatusChanged(object sender, EventArgs eventArgs)
{
if (lvResultado.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
var index = lvResultado.SelectedIndex;
if (index >= 0)
{
var item = lvResultado.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
if (item != null)
{
item.Focus();
}
}
}
}
Specifically, I want to write something like: local:FocusFirstElement.Focus="True" in my XAML instead of writing this code for every list view.
What you are is really an attached behavior, which is implemented via an attached property which is really a special dependency property (which you seem to have hit upon already).
First, create an attached property. This is most easliy accomplished using the propa snippet:
public static bool GetFocusFirst(ListView obj)
{
return (bool)obj.GetValue(FocusFirstProperty);
}
public static void SetFocusFirst(ListView obj, bool value)
{
obj.SetValue(FocusFirstProperty, value);
}
public static readonly DependencyProperty FocusFirstProperty =
DependencyProperty.RegisterAttached("FocusFirst", typeof(bool),
typeof(ListViewExtension), new PropertyMetadata(false));
I'm assuming this is in a static class called ListViewExtenstion. Then, handle the property changed event:
public static readonly DependencyProperty FocusFirstProperty =
DependencyProperty.RegisterAttached("FocusFirst", typeof(bool),
typeof(ListViewExtension), new PropertyMetadata(false, HandleFocusFirstChanged));
static void HandleFocusFirstChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
}
In that handler you would check the current value (in e) and register or deregister for the appropriate event on the ListView contained in depObj. Then you would use your existing code to set the focus. Something like:
static void HandleFocusFirstChanged(
DependencyObject depObj, DependencyPropertyChangedEventArgs e)
{
ListView lv = (ListView)debObj;
if ((bool)e.NewValue)
lv.StatusChanged += MyLogicMethod;
}

Silverlight detect when Dependency property has a Xaml binding

Is it possible to detect when a Xaml binding is set on a DependencyProperty in Silverlight?
E.g. if I had a custom user-control with single dependency property and a binding declared like this:
public class MyControl : UserControl
{
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("Test",
typeof(object), typeof(MyControl),
new PropertyMetadata(null));
public object Test
{
get { return GetValue(TestProperty); }
set { SetValue(TestProperty, value); }
}
}
<MyControl Test="{Binding APropInViewModel}>
</MyControl>
Can I in the MyControl code to something like this?
// Ctor
public MyControl()
{
TestProperty.BindingChanged += new EventHandler(...)
}
e.g. can I get a notification of binding?
NOTE:
This is to solve a tricky order of precedence problem, described here so just checking for new values in the DependencyPropertyChanged handler won't work - because the property changed handler doesn't fire!!
It is possible for value changes in this binding. You can detect changes using propertychanged callback method which is static for Dependency properties.
public static readonly DependencyProperty TestProperty =
DependencyProperty.Register("Test",
typeof(object), typeof(MyControl),
new PropertyMetadata(null, TestChangedCallbackHandler));
private static void TestChangedCallbackHandler(DependencyObject sender, DependencyPropertyChangedEventArgs args)
{
MyControl obj = sender as MyControl;
Test = args.NewValue;
}
However, this might cause following event listening cases. If you want to listen changes on this dependency property is explained in this link :
Listen DepencenyProperty value changes
public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{
Binding b = new Binding(propertyName) { Source = element };
var prop = System.Windows.DependencyProperty.RegisterAttached(
"ListenAttached" + propertyName,
typeof(object),
typeof(UserControl),
new System.Windows.PropertyMetadata(callback));
element.SetBinding(prop, b);
}
and call like this
this.RegisterForNotification("Test", this, TestChangedCallback);

Get the value of an attached property rather than set it

I have some code to set the focused property of a text box, but what i'm actually after is finding out if the text box currently has the keyboard focus, I need to determine this from my view model
public static class FocusExtension
{
public static bool GetIsFocused(DependencyObject obj)
{
return (bool)obj.GetValue(IsFocusedProperty);
}
public static void SetIsFocused(DependencyObject obj, bool value)
{
obj.SetValue(IsFocusedProperty, value);
}
public static readonly DependencyProperty IsFocusedProperty = DependencyProperty.RegisterAttached
(
"IsFocused",
typeof(bool),
typeof(FocusExtension),
new UIPropertyMetadata(false, OnIsFocusedPropertyChanged)
);
public static void OnIsFocusedPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var uie = (UIElement)d;
if ((bool)e.NewValue)
{
uie.Focus();
}
}
}
And the xaml is
<TextBox Text="{Binding Path=ClientCode}" c:FocusExtension.IsFocused="{Binding IsClientCodeFocused}" />
source of code
have you seen the FocusManager? you can get/set focus using this object.
Edit
Based on the comments below, here's an example of an attached property that hooks up an event and updates the source of a binding. I'll add comments where I know you'll need to make modifications. Hopefully it will point you in the right direction
public class TextBoxHelper
{
// I excluded the generic stuff, but the property is called
// EnterUpdatesSource and it makes a TextBox update it's source
// whenever the Enter key is pressed
// Property Changed Event - You have this in your class above
private static void EnterUpdatesTextSourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
UIElement sender = obj as UIElement;
if (obj != null)
{
// In my case, the True/False value just determined a behavior,
// so toggling true/false added/removed an event.
// Since you want your events to be on at all times, you'll either
// want to have two AttachedProperties (one to tell the control
// that it should be tracking the current focused state, and
// another for binding the actual focused state), or you'll want
// to find a way to only add the EventHandler when the
// AttachedProperty is first added and not toggle it on/off as focus
// changes or add it repeatedly whenever this value is set to true
// You can use the GotFocus and LostFocus Events
if ((bool)e.NewValue == true)
{
sender.PreviewKeyDown += new KeyEventHandler(OnPreviewKeyDownUpdateSourceIfEnter);
}
else
{
sender.PreviewKeyDown -= OnPreviewKeyDownUpdateSourceIfEnter;
}
}
}
// This is the EventHandler
static void OnPreviewKeyDownUpdateSourceIfEnter(object sender, KeyEventArgs e)
{
// You won't need this
if (e.Key == Key.Enter)
{
// or this
if (GetEnterUpdatesTextSource((DependencyObject)sender))
{
// But you'll want to take this bit and modify it so it actually
// provides a value to the Source based on UIElement.IsFocused
UIElement obj = sender as UIElement;
// If you go with two AttachedProperties, this binding should
// point to the property that contains the IsFocused value
BindingExpression textBinding = BindingOperations.GetBindingExpression(
obj, TextBox.TextProperty);
// I know you can specify a value for a binding source, but
// I can't remember the exact syntax for it right now
if (textBinding != null)
textBinding.UpdateSource();
}
}
}
There might be a better way of accomplishing what you're trying to do, but if not then I hope this provides a good starting point :)
in your OnIsFocusedPropertyChanged handler, you need to get a reference to the control that it is being set on and subscribe to its FocusChanged event, where you can re-set the dependency pproperty. Make sure in your XAML you set the binding mode to TwoWay

WPF :: Custom control how to Fire a method when a user change a property

Hello
I created a custom control class that its derived from a Grid, so is there a function to override when a user change a property? for example if i have a property called Count how can i know when the user change the count property ?
Thanks alot
EDIT
i'm doing some progress
protected override void OnPropertyChanged(System.Windows.DependencyPropertyChangedEventArgs
e){
}
now on my designer window the custom control doesn't change when i change the property i will have to run the code and close it to see the difference on my designer window how can i solve that?
If it is dependency property then use:
public static readonly DependencyProperty CountProperty =
DependencyProperty.Register("Count", typeof(int), typeof(YourClass), new UIPropertyMetadata(OnCountChanged));
public int Value
{
get { return (int)GetValue(CountProperty); }
set { SetValue(CountProperty, value); }
}
private static void OnCountChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
YourClass cp = obj as YourClass;
MethodToExecute();
}
You can subscribe to the NotifyPropertyChanged event:
in your constructor put the following:
this.NotifyPropertyChanged += (sender, eventargs) =>
{
if (eventargs.PropertyName == "Count")
this.CountChanged();
};

Change non static object from static Context

I have next dependecy property:
public static DependencyProperty IsInReadModeProperty =
DependencyProperty.Register("IsInReadMode", typeof(bool),
typeof(RegCardSearchForm), new PropertyMetadata(false, ReadModeChanged));
and I have next method which handle Property changed event:
public static void ReadModeChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
btnSearch.Visibility = Visibility.Collapsed;
btnExport.Visibility = Visibility.Collapsed;
cbExportWay.Visibility = Visibility.Collapsed;
}
}
But compiler give me error that i cannot acces non static buttons (btnSearch and e.t.c ) in static context.
I want change visibility of buttons when property value changed. How can I resolve this situation?
Since (non-attached) DependencyProperties are restricted to being set on their owner type you can just create an instance method to hold your logic and call that from the static method by casting the DependencyObject:
public static readonly DependencyProperty IsInReadModeProperty = DependencyProperty.Register(
"IsInReadMode",
typeof(bool),
typeof(RegCardSearchForm),
new UIPropertyMetadata(false, ReadModeChanged));
private static void ReadModeChanged(DependencyObject dObj, DependencyPropertyChangedEventArgs e)
{
RegCardSearchForm form = dObj as RegCardSearchForm;
if (form != null)
form.ReadModeChanged((bool)e.OldValue, (bool)e.NewValue);
}
protected virtual void ReadModeChanged(bool oldValue, bool newValue)
{
// TODO: Add your instance logic.
}
One way could be to extend a class from DependencyObject that would contain the set/get of the controls that you want to manipulate. And process it in ReadModeChanged event by accessing DependencyObject.
This example might help.
... example derives from DependencyObject to create a new abstract class. The class then registers an attached property and includes support members for that attached property.
If ReadModeChanged is a static method of the container for your buttons, then just make it an instance method of the container.
These things do have to be static in order for a DependencyProperty to work properly However, the parameter to your PropertyChanged handler is probably the thing you need: it's the instance whose property has just changed. I suspect this would work for you:
public static void ReadModeChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
if ((bool)e.NewValue)
{
RegCardSearchForm c = (RegCardSearchForm)d;
c.btnSearch.Visibility = Visibility.Collapsed;
c.btnExport.Visibility = Visibility.Collapsed;
c.cbExportWay.Visibility = Visibility.Collapsed;
}
}

Categories