Home > Net >  Can I Bind from UserControl to DataTemplate?
Can I Bind from UserControl to DataTemplate?

Time:12-20

I want to bind from UserControl to DataTemplate.

But I get error

Cannot find source for binding with reference 'ElementName=LoginTextBox'. BindingExpression:(no path); DataItem=null; target element is 'Grid' (Name=''); target property is 'FocusedElement' (type 'IInputElement')

My code

<UserControl>
    <UserControl.Resources>
        
        <DataTemplate DataType="{x:Type models:LocalAuthenticationMethod}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="72"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <TextBlock Grid.Column="0" VerticalAlignment="Center"
                       Text="{uiCommon:LocalizationBinding ResourceName=Login}"
                       FontSize="{DynamicResource LoginWindowPropertiesFontSize}"/>
                
                <!-- bind to here -->
                <ComboBox x:Name="LoginTextBox"
                      Grid.Column="1"
                      Height="24"
                      Text="{Binding ElementName=Root, Path=DataContext.Login, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, NotifyOnTargetUpdated=True}"
                      ItemsSource="{Binding ElementName=Root, Path=DataContext.AvailableUsers, Mode=OneWay}"
                      IsEditable="True"
                      behavior:FocusAdvancement.AdvancesByEnterKey="True"
                      FontSize="{DynamicResource LoginWindowPropertiesFontSize}">
                    <b:Interaction.Behaviors>
                        <behavior:SelectTextOnGotFocusBehavior/>
                        <behavior:SelectTextOnTargetUpdatedBehavior/>
                    </b:Interaction.Behaviors>
                </ComboBox>
            </Grid>
        </DataTemplate>
    </UserControl.Resources>
    <Grid x:Name="Root">

        <!-- how to bind here? -->
        <Grid FocusManager.FocusedElement="{Binding ElementName=LoginTextBox}"> 
            <ContentControl>
                <ContentPresenter Content="{Binding SelectedAuthenticationMethod, Mode=OneWay}"/>
            </ContentControl>
        </Grid>
    </Grid>
</UserControl>

I want to bind FocusedElement to ElementName=LoginTextBox. How can I do it? Is it possible at all?

CodePudding user response:

Is it possible at all?

No, because the name "LoginTextBox" is only available inside the DataTemplate where the ComboBox is defined.

The Grid resides in a different XAML namescope that doesn't know anything about the individual elements that defines the visual appearance of a LocalAuthenticationMethod object.

  • Related