Monday, October 19, 2015

Binding to a user control property

This is for Framework 4.0.

I have a page with a user control on it. The user control contains a list and I want to display the count of items in the list in a text block on the main page. It was obvious I would need to create a dependency property in the user control, so...

Public Shared ReadOnly CountProperty As Windows.DependencyProperty = Windows.DependencyProperty.Register("AttachmentCount", GetType(Integer), GetType(Attachments), Nothing)

Public Property AttachmentCount As Integer
Get
    Return CInt(GetValue(CountProperty))
End Get
Set(value As Integer)
    SetValue(CountProperty, value) 
End Set
End Property

Now it's a simple matter of binding the textblock to the user control's property, right?

<TextBlock Name="AddAttachmentsCount" Text="{Binding ElementName=AddAttachmentsUserControl, Path=AttachmentCount"/>

Oops, now I'm seeing an error in the output window at run-time...


System.Windows.Data Error: 40 : BindingExpression path error: '(AttachmentCount)' property not found on 'object' ''UserControl' (Name='AddAttachmentsUserControl')'. BindingExpression:Path=AttachmentCount; DataItem='UserControl' (Name='AddAttachmentsUserControl'); target element is 'TextBlock' (Name='AddAttachmentsCount'); target property is 'Text' (type 'String')

Well maybe I can bind the AttachmentCount property to the text property of my textblock as I define the instance of my user control...


<local:Attachments x:Key="AddAttachments" AttachmentCount="{Binding ElementName=AddAttachmentsCount, Path=Text, Mode=TwoWay}"/>

Yay!


1 comment: