none
Binding to UserControl's dependency property RRS feed

  • Question

  • Hello, I have a UserControl, which declares a dependency property.

     

    public partial class CultureControl : UserControl

    {

    public static readonly DependencyProperty SelectedCultureProperty = DependencyProperty.Register("SelectedCulture", typeof(CultureInfo), typeof(CultureControl));

    ...

    private void CultureControl_Loaded(object sender, RoutedEventArgs e)

    {

    CultureCombo.ItemsSource = CultureInfo.GetCultures(CultureTypes.NeutralCultures);

    }

    ...

    }

     

    <UserControl ...>

     

    <ComboBox Name="CultureCombo" IsEditable="True" SelectedValue="{Binding Path=SelectedCulture, Mode=TwoWay}" DisplayMemberPath="DisplayName" />

     

    </UserControl>

     

    However, it seems that this binding does not work (eg. dependency property changed event is not fired and setting its value does not select the item in the combo), although no error is written in the output window.

     

    1) How should I set the binding to bind to this property?

    2) Is TwoWay explicitly setting needed in this case?

    Sunday, August 12, 2007 5:27 PM

Answers

  • You can achieve a similar thing in the xaml by adding

    Code Snippet

    DataContext="{Binding RelativeSource={RelativeSource Self}}"


    to the UserControl tag.

    Alternatively without the DataContext on the user control you could bind by specifying the relative source to be the first UserControl ancestor:

    Code Snippet

    SelectedValue="{Binding Path=SelectedCulture, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"


    Hope that helps,

    Antin
    Monday, August 13, 2007 2:17 AM

All replies

  • Well I figured out that setting DataContext = this in Loaded event makes bindings work, which is not so surprising. But I'd rather to set some source on the Binding, to avoid this trick.

    Sunday, August 12, 2007 6:50 PM
  • You can achieve a similar thing in the xaml by adding

    Code Snippet

    DataContext="{Binding RelativeSource={RelativeSource Self}}"


    to the UserControl tag.

    Alternatively without the DataContext on the user control you could bind by specifying the relative source to be the first UserControl ancestor:

    Code Snippet

    SelectedValue="{Binding Path=SelectedCulture, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}"


    Hope that helps,

    Antin
    Monday, August 13, 2007 2:17 AM