I have a control which has a button named “btn1”, and I want to change it’s contents through a dependency property in xaml, like this:
<UserControl:UserControl1 ButtonContents="Something"/>
Here’s what I have:
Public Class UserControl1
Public Shared ReadOnly ButtonContentsProperty As DependencyProperty =
DependencyProperty.Register("ButtonContents",
GetType(String),
GetType(UserControl.UserControl1))
Public Property ButtonContents() As Boolean
Get
Return GetValue(ButtonContentsProperty)
End Get
Set(ByVal value As Boolean)
SetValue(ButtonContentsProperty, value)
End Set
End Property
End Class
But how can the dependency property know what to do?
The solution is based upon the following approach – button’s content gets defined as a resource belonging to the button itself. Unfortunately ResourceKey is not a DP and hence cannot be bound, we created an attached property BindiableResourceKey which subsistutes for that. The user control has a property ButtonLook of string type which holds the name of the resource to be used as button’s content. If you need to implement more complex linking logic just extend the attached property value changed handler.
Here’s the code:
Part1 – User Control:
Part 2 – Attached Property:
Part 3 – Consumer: