The problem was that I wasn't getting the right control when I used Keyboard.FocusedElement. This may be a devexpress thing as I use their controls. So traversing the element tree upwards until I get that control solved my problem... Thank you Clemens!
cannot get attached property value
-
31-05-2022 - |
質問
Hi I hope I can find some help here...
I am creating a WPF application using prism and MVVM.
I am trying to create an attached property which i found here.
in my ViewModel I get the focused Element by
var control = Keyboard.FocusedElement;
then I do
string value = ExtraTextBehaviourObject.GetExtraText(control as UIElement);
but the value returned is always null... Can anyone point me to the right direction???
UPDATE
public class ExtraTextBehaviourObject : DependencyObject
{
//Declare the dependency property
public static readonly DependencyProperty ExtraTextProperty;
static ExtraTextBehaviourObject()
{
//register it as attached property
ExtraTextProperty = DependencyProperty.RegisterAttached("ExtraText", typeof(string),
typeof(ExtraTextBehaviourObject));
}
//static function for setting the text
public static void SetExtraText(UIElement uiElement, string value)
{
if (uiElement != null)
{
uiElement.SetValue(ExtraTextProperty, value);
}
}
//static function for getting the text
public static string GetExtraText(UIElement uiElement)
{
if (uiElement != null)
{
return (string)uiElement.GetValue(ExtraTextProperty);
}
return "";
}
}
Set code in XAML
<dxe:TextEdit Text="{Binding Path=Customer.Comments, Mode=TwoWay}" AcceptsReturn="True" VerticalContentAlignment="Top"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Behaviors:ExtraTextBehaviourObject.ExtraText="HelloExtraText"
ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto"/>
解決
他のヒント
Just an additional idea: Instead of traversing the tree by hand yourself, you could let WPF do that for you. Flag your attached property with FrameworkPropertyMetadataOptions.Inherits
now the value can be retrieved by all children of the initial control where you set the attached property.
For example
<Grid MyService.MyProperty="True">
<TextBox .../>
var txt = aSender as TextBox;
var val = MyService.GetMyProperty(txt);
With Inherits
GetMyProperty
will return true
, because it "inherits" the value from his parent Grid, without inherit of course the value would be false
(not null, because its a value type).
DataContext
for example is also an inherited dependency property.