【问题标题】:Wpf, How to find Element name from one user control in anotherWpf,如何从另一个用户控件中查找元素名称
【发布时间】:2014-11-04 09:16:10
【问题描述】:
    <TextBox x:Name="DescriptionTextBox" 
             Text="{Binding SelectedEntity.Description,
                            ValidatesOnExceptions=True}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="LostFocus" SourceName="DescriptionTextBox">
                <ei:CallMethodAction MethodName="RaiseCanExecuteChanged" 
                TargetObject="{Binding Command, ElementName=SaveButton}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>

    <userControls:SaveCloseUserControl />

在这个用户控件中

<StackPanel HorizontalAlignment="Right" Orientation="Horizontal">
    <Button Width="50"
            Command="{Binding SaveCommand}"
            Content="Save" />
    <Button Width="50"
            Command="{Binding CloseCommand}"
            Content="Close" />
 </StackPanel>

这里的问题是这个 TargetObject="{Binding Command, ElementName=SaveButton}" 没有找到 SaveButton 因为它在 userControls:SaveCloseUserControl 我在网上看了看,发现了一个需要代码的解决方案(从 2009 年开始),今天有没有一种简单的方法来做这些事情? 问候

编辑

根据@huzle 的回答,我在用户控件后面的代码中执行了此操作

    public object CreateButton { get { return CreateChild; } }

在 xaml 中,我为保存按钮添加了一个名称。

所以我的最终版本看起来像这样

    <TextBox x:Name="DescriptionTextBox" 
             Text="{Binding SelectedEntity.Description,
                            ValidatesOnExceptions=True}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="LostFocus" SourceName="DescriptionTextBox">
                <ei:CallMethodAction MethodName="RaiseCanExecuteChanged" 
                TargetObject="{Binding CreateButton.Command,ElementName=MySaveCloseUserControl}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>

    <userControls:SaveCloseUserControl x:Name="MySaveCloseUserControl"/>

【问题讨论】:

    标签: wpf xaml user-controls elementname


    【解决方案1】:

    为您的“SaveCloseUserControl”提供名为“InnerSaveButton”的“SaveButton”的公共属性,并将 ElementName 绑定到您的 SaveCloseUserControl,并使用 Path 获取内部按钮的命令。

    <TextBox x:Name="DescriptionTextBox" 
             Text="{Binding SelectedEntity.Description,
                            ValidatesOnExceptions=True}">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="LostFocus" SourceName="DescriptionTextBox">
                <ei:CallMethodAction MethodName="RaiseCanExecuteChanged" 
                TargetObject="{Binding InnerSaveButton.Command, ElementName=MySaveCloseUserControl}" />
            </i:EventTrigger>
        </i:Interaction.Triggers>
    </TextBox>
    
    <userControls:SaveCloseUserControl X:Name="MySaveCloseUserControl"/>
    

    【讨论】:

      猜你喜欢
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多