I created a user control and wanted to get the value of the DependencyProperty "ListBoxReadOnly" in the code. I set the value in the XAML:
<control:AutoCompleteTextBox x:Name="actbFullName" ListBoxReadOnly="True"/>
When I tried to read the value in the constructor, it only shows the default value which is false.
I tried to get the value via a callback back but probably I am lacking some understanding of the whole framework. Since the callback is a static method, I cannot apply it to the instance of my user control.
public static readonly DependencyProperty ListBoxReadOnlyDependency =
DependencyProperty.Register("ListBoxReadOnly", typeof(bool),
typeof(AutoCompleteTextBox), FrameworkPropertyMetadata
(false, FrameworkPropertyMetadataOptions.AffectsRender));
public bool ListBoxReadOnly
{
get
{
return (bool) GetValue(ListBoxReadOnlyDependency);
}
set
{
SetValue(ListBoxReadOnlyDependency, value);
}
}
// constructor of user control
public AutoCompleteTextBox()
{
InitializeComponent();
// *** shows "false" (default value) even though set to true in XAML
// *** see XAML above ***
var test = ListBoxReadOnly;
}
Any help is appreciated :-)
I would expect your code (as is) to show false. The DP is initialized to false. In the constructor of your control, neither the default control style, nor the properties set in xaml have been applied yet.
The style is only applied after OnApplyTemplate() is called (unless you force it).
If you want to track DP changes, you need a DP change handler.