Search code examples
silverlightxamlmvvmsilverlight-5.0

Silverlight set property path in converter?


I have a Listbox, that has multiple datatemplates for it's items. The datatemplate is selected using a converter and interpreting the object collection of the ListBox.

Inside of the converter I am trying to bind a property from the datacontext (outside of the lisbox) to the datatemplate's TextBox control.

ListBox:

<telerik:RadListBox
            x:Name="listBox2"
            ItemsSource="{Binding MyCollection, Mode=TwoWay}"
            VerticalAlignment="Top" Height="400">

            <telerik:RadListBox.ItemTemplate>
                <DataTemplate>
                    <ContentControl Content="{Binding}"
                                    ContentTemplate="{Binding Converter={StaticResource myTestConverter}, ConverterParameter={StaticResource myViewModel}}" />
                </DataTemplate>
            </telerik:RadListBox.ItemTemplate>
        </telerik:RadListBox>

The DataTemplate:

<DataTemplate x:Key="TestResource1">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding propertyLabel}"
                       FontStyle="Italic" Width="120" />
            <TextBox x:Name="valueField"  
                       FontSize="12" Width="50"
                       FontWeight="Bold" />
        </StackPanel>
    </DataTemplate>

Inside the Converter's convert method:

_dt = Application.Current.Resources["TestResource1"] as DataTemplate;
                var context = _dt.LoadContent();

                var ctrl = FindControlByType<TextBox>(context, "valueField");

                Binding binding = new Binding("DataContext.Value1");
                binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor) { AncestorType = typeof(MainPage) };

                TextBox txtBox = ctrl as TextBox;
                BindingOperations.SetBinding(txtBox, TextBox.TextProperty, binding);

This doesen't work. Any idea what I am doing wrong?

Thank you.


Solution

  • The reason LoadContent isn't working for you is because this is usually called by the control itself during OnApplyTemplate().

    In this type of situation, I found it easier to use XamlReader.Load() to load a custom piece of DataTemplate and then assigning it to the control.