【问题标题】:Get Control (Button) from parent in usercontrol从用户控件中的父级获取控件(按钮)
【发布时间】:2021-06-09 14:46:34
【问题描述】:

我有一个窗口,其中包含不同的项目和每种类型的不同视图。 我想从内容控件后面的代码中访问窗口(父)中的按钮。

输出配置视图:

                    <ContentControl Margin="5">
                    <ContentControl.Style>
                        <Style TargetType="ContentControl">
                            <Style.Triggers>
                                <DataTrigger Binding="{Binding SelectedOutputRendererTyp}" Value="{x:Type outTypes:XmlBarcodeRenderer}">
                                    <Setter Property="ContentTemplate" Value="{StaticResource OutputRendererView}"/>
                                </DataTrigger>
                                <DataTrigger Binding="{Binding SelectedOutputRendererTyp}" Value="{x:Type outTypes:CsvBarcodeRenderer}">
                                    <Setter Property="ContentTemplate" Value="{StaticResource CsvOutputRendererView}"/>
                                </DataTrigger>
                            </Style.Triggers>
                        </Style>
                    </ContentControl.Style>
                </ContentControl>                          
                      .
                      .

        <Button x:Name="CloseButton"
                Grid.Column="1"
                Click="WindowClose"
                Content="Ok"
                Margin="0 0 0 -5"
                HorizontalAlignment="Center" 
                VerticalAlignment="Bottom">
        </Button>

OutputRendererView.xaml.cs:

 public partial class OutputRendererView : UserControl
{
    public OutputRendererView()
    {
        InitializeComponent();
    }

    private void Border_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
         var parentWindow = (OutputRendererView)this.Parent;
         var button = (Button)parentWindow.FindName("CloseButton");
    }

在这种情况下,parentWindow 为空。

如何从我的控件背后的代码访问调用窗口的按钮?

【问题讨论】:

    标签: c# wpf code-behind contentcontrol visual-tree


    【解决方案1】:

    要访问用户控件内的按钮,您必须先找到usercontrol,然后再找到其中的button。

    var button = (Button)((UserControl)parentWindow.FindName("userControlName")).FindName("CloseButton");
    

    【讨论】:

    • 按钮在父视图(OutputConfigView)中,我没有得到父视图。
    猜你喜欢
    • 2013-09-02
    • 1970-01-01
    • 2013-05-21
    • 1970-01-01
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多