views:

15

answers:

1

to date I have created and setup bindings and dependencies between controls and other objects when they are located within the same directory or within the same xaml document.

Now I have created a usercontrol which is located in a directory of my project called "Controls" this control is then loaded within the main xaml document using the tag

my question is how do I go about setting up bindings between the objects within the user control and objects within the main xaml document.

An example of this would be if I have a textbox within my user control and within the main xaml page I have a checkbox. When the checkbox is clicked I want to set the visibility of the the textbox to Collapsed.

As I said I have been able to do this when both objects are within the same document But now since the text field is placed inside a user control and within a directory I am unsure of how to reference it.

Thank you

A: 

Add a DependencyProperty to your UserControl. In your main window's XAML, bind to the DependencyProperty. In your UserControl's XAML, bind to the same DependencyProperty using RelativeSource FindAncestor.

For example if your UserControl is called "MyUserControl" and has a DependencyProperty "ShowDetails", the binding in the main XAML would be:

<Window ...>
  ...
  <local:MyUserControl ShowDetails="{Binding IsChecked,ElementName=checkBox}" />
  ...
  <CheckBox x:Name=checkBox Content="Show Details" />
  ...
</Window>

and in the UserControl's XAML it would be:

<UserControl ...>
  ...
  <Textbox ...
     Visibility="{Binding ShowDetails,
       RelativeSource={RelativeSource FindAncestor,local:MyUserControl,1},
       Converter={StaticResource BoolToVisibiltyConverter}" />
  ...
</UserControl>

Better yet, use the MVVM pattern. In this case you would put the DependencyProperty in your ViewModel which would be accessible throught the DataContext of both your main window and your UserControl. With MVVM there is no need to use FindAncestor or ElementName because both the CheckBox and the TextBox bind directly to the property in the ViewModel:

<Window ...>

  <local:MyUserControl />
  ...
  <CheckBox IsChecked="{Binding ShowDetails}" Content="Show Details" />

</Window>

with this UserControl:

<UserControl>
  ...
  <TextBox ...
     Visibility="{Binding ShowDetails,
       Converter={StaticResource BoolToVisibiltyConverter}" />
  ...
</UserControl>
Ray Burns