Wpf,如何从另一个用户控件中找到元素名称

时间:2014-11-04 09:16:10

标签: wpf xaml user-controls elementname

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

1 个答案:

答案 0 :(得分:1)

提供你的&#34; SaveCloseUserControl&#34; &#34; SaveButton&#34;的公共属性命名&#34; InnerSaveButton&#34;并使用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"/>