Videos | Podcasts

DataBinding Custom Properties Using User Controls in WPF
AzamSharp
Published Date: 1/5/2009 11:22:12 AM
Views: 4971

Abstract:
WPF databinding simplyfies many complex operations and allows to achieve the result by only using the XAML code. In this article we will demonstrate how to use a custom dependency property in a databinding operation inside a user control.

Introduction:

WPF databinding simplyfies many complex operations and allows to achieve the result by only using the XAML code. In this article we will demonstrate how to use a custom dependency property in a databinding operation inside a user control.

Simple DataBinding:

Let's say we want to display the SelectedItem text from the ComboxBox in a Label control. Here is the code which is not using the databinding powers of WPF.


 <Grid>
        
        <StackPanel>            
            <ComboBox Name="cbItems" Width="100" SelectionChanged="cbItems_SelectionChanged" Height="20"></ComboBox>
            
            <Label Name="lblSelectedItem"  Width="100"></Label>
            
            
        </StackPanel>
    </Grid>


And here is the cbItems_SelectionChanged event.



  private void cbItems_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            lblSelectedItem.Content = (cbItems.SelectedItem as ComboBoxItem).Content;
        }



Now, if you select an item from the ComboBox the Label will display the Text of the SelectedItem.

The above code will work correctly but this can easily be achieved using WPF databinding operation. Check out the code below which is used to solve this using WPF.


 <Grid>
        
        <StackPanel>            
            <ComboBox Name="cbItems" Width="100" Height="20"></ComboBox>
            
            <Label Name="lblSelectedItem" Content="{Binding ElementName=cbItems, Path=SelectedItem.Content}"  Width="100"></Label>
            
            
        </StackPanel>
    </Grid>


As, you can see that we only used the XAML code to acheive the desired result.

Creating FileInputBox User Control:

The example discussed in this article came from WPF Unleashed by Adam Nathan. We will create a user control FileInputBox. The purpose of the control is to display the selected file into the TextBox. The file will be selected from the client's machine by using the OpenFileDialog control.

Here is the XAML code for the FileInputBox control which creates a Button and TextBox.


  <StackPanel>
            <TextBox Name="txtFileName" Width="300" Height="20"></TextBox>
            <Button Name="BtnSelectFile" Content="Browse..." Width="100" Height="20" Click="BtnSelectFile_Click"></Button>
        </StackPanel>


The BtnSelectFile_Click is responsible for popping up the OpenFileDialog. The implementation is shown below:


 private void BtnSelectFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.ShowDialog();

            this.FileName = fileDialog.FileName;
        }


The FileName is a string property which returns the value in the DependencyProperty. Let's see the implementation of the DependencyProperty.



 public static readonly DependencyProperty FileNameProperty = DependencyProperty.Register("FileName",
                                                                                                 typeof (String),
                                                                                                 typeof (FileInputBox));

   public string FileName
        {
            get { return (string) GetValue(FileNameProperty);  }
            set { SetValue(FileNameProperty, value); }

        }



Now, let's add the databinding expression to the XAML code to use the FileName property.


 <TextBox Name="txtFileName" Text="{Binding FileName, ElementName=root}" Width="300" Height="20"></TextBox>


The name of the user control is "root".

Finally, let's add the control to the Window.


<Window x:Class="WPF3D.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="300" Width="300"
        xmlns:local="clr-namespace:WPF3D"
         >
           
    <Grid>        
        <StackPanel>                       
            <local:FileInputBox></local:FileInputBox>            
        </StackPanel>
    </Grid>
</Window>



When you run the above code you will see the user control inside your window. Select a file using the browse button and see the name of the file appear in the TextBox control. Wait! it does not appear in the TextBox control. This is a gotcha in WPF when using databinding with custom dependency properties. The workaround is to create a callback method which will be called when the dependency property is changed.

Here is the modified code for the dependency property:


 public static readonly DependencyProperty FileNameProperty = DependencyProperty.Register("FileName",
                                                                                                 typeof (String),
                                                                                                 typeof (FileInputBox),new UIPropertyMetadata(
                                                                                                     String.Empty,
                                                                                                     textChangedCallback));

        private static void textChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FileInputBox input = (FileInputBox) d;
            input.txtFileName.Text = e.NewValue as String;
        }


Now, if you run the above code it will work as expected.

Conclusion:

In this article we learned how to create a custom dependency property and use it with our own user control. We also learned about a small tip when using databinding with custom dependency properties.

References:

1) WPF Unleashed by Adam Nathan
2) WPF Custom Control Dependency Property Gotcha

[Download Sample]



Did you like this article?
kick it on DotNetKicks.com Submit
Similar Articles

Creating WPF Live Counter as Background

Creating SharpRichTextBox for Live Character Count in WPF

Understanding Events in Windows Presentation Foundation

Creating a Simple RSS Reader Using Windows Presentation Foundation

Creating WPF TextBox UserControl to Perform Custom Validation

Enter Comment/Feedback

 
 
 
 
 

Comments/Feedbacks