【问题标题】:Can I Bind from UserControl to DataTemplate?我可以从 UserControl 绑定到 DataTemplate 吗?
【发布时间】:2022-01-20 05:05:21
【问题描述】:

我想从 UserControl 绑定到 DataTemplate。

但我得到错误

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')

我的代码

<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>

我想将 FocusedElement 绑定到 ElementName=LoginTextBox。我该怎么做?有可能吗?

【问题讨论】:

  • “有可能吗?” - 不,不是
  • @ASh :( 我们将不得不放弃数据模板并使用触发器

标签: c# wpf bind


【解决方案1】:

有可能吗?

否,因为名称“LoginTextBox”仅在定义了ComboBoxDataTemplate 内可用。

Grid 位于不同的 XAML namescope 中,它对定义 LocalAuthenticationMethod 对象的视觉外观的各个元素一无所知。

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 2012-08-28
    • 2012-09-30
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    相关资源
    最近更新 更多