Reputation: 15794
I have the following attached property definition:
public class TestFocusManager
{
public static readonly DependencyProperty FocusedElementProperty =
DependencyProperty.RegisterAttached("FocusedElement",
typeof (UIElement), typeof(TestFocusManager));
public static UIElement GetFocusedElement(DependencyObject obj)
{
return (UIElement) obj.GetValue(FocusedElementProperty);
}
public static void SetFocusedElement(DependencyObject obj, UIElement value)
{
obj.SetValue(FocusedElementProperty, value);
}
}
When I try to use it in my user control:
<UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
xmlns:Behaviors="clr-namespace:MyLocalProject.Behaviors"
Behaviors:TestFocusManager.FocusedElement="{Binding ElementName=testElement}"
x:Class="LocalProject.TestView"
x:Name="_testView">
<TextBox x:Name="testElement" />
</UserControl>
The attached property always returns a null...
var result = TestFocusManager.GetFocusedElement(_testView); // <-- null...
var result2 = _testView.GetValue(TestFocusManager.FocusedElementProperty); // <-- again, null...
What am I doing wrong here? Thanks in advance!
Upvotes: 2
Views: 1093
Reputation: 861
local:TestFocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"
you can get a reference to the user control itself and expose a public property which gives out a button. You can use this as a last resort !.
Btw whenever I have had issues with attached properties. I generally tend to put a callback or change the type to that of Object, I mean instead of UIElement tend to use object atleast I get a callback and check whats the exact type comes as a part of callback
Cheers
Upvotes: 0
Reputation: 25201
Your problem is that GetFocusedElement
is called before the binding is actually set (you're probably calling it in the UserControl's constructor). If you call it in the Loaded
event, it should be fine.
Upvotes: 1
Reputation: 11252
I tested your code and it works fine for me except you omitted the "public" keyword in your Dependency Property setter.
I'm assuming that's a typo, if not then that's you're problem.
Upvotes: 0