C# 如何在WPF中使用StackPanel.FindName?

C# 如何在WPF中使用StackPanel.FindName?,c#,wpf,C#,Wpf,我有一个堆栈面板,里面有一组四个图像按钮。当我尝试按图像按钮的名称搜索时,返回空值。我的代码有什么问题 XAML: <StackPanel x:Name="swatchClearStackPanel" Orientation="Vertical" Grid.Column="1" Grid.Row="2" Margin="0,10,0,0" HorizontalAlignment="Left" VerticalAlignment="Bottom"> <imgbutton

我有一个堆栈面板,里面有一组四个图像按钮。当我尝试按图像按钮的名称搜索时,返回空值。我的代码有什么问题

XAML:

<StackPanel x:Name="swatchClearStackPanel" Orientation="Vertical" Grid.Column="1" Grid.Row="2" Margin="0,10,0,0" HorizontalAlignment="Left" VerticalAlignment="Bottom">
     <imgbutton:ImageButton x:Name="ClearSwatchColor1" Grid.Row="0" Grid.Column="2" Style="{DynamicResource ButtonClearSwatchColor}" Margin="5,8,5,5" HorizontalAlignment="Left"  Visibility="Hidden" Click="ClearSwatchColor_Click"  />
     <imgbutton:ImageButton x:Name="ClearSwatchColor2"  Grid.Row="0" Grid.Column="2" Style="{DynamicResource ButtonClearSwatchColor}"  Margin="5,18,5,5" HorizontalAlignment="Left"  Visibility="Hidden" Click="ClearSwatchColor_Click"/>
     <imgbutton:ImageButton x:Name="ClearSwatchColor3"  Grid.Row="0" Grid.Column="2" Style="{DynamicResource ButtonClearSwatchColor}"  Margin="5,18,5,5" HorizontalAlignment="Left"  Visibility="Hidden" Click="ClearSwatchColor_Click"/>
     <imgbutton:ImageButton x:Name="ClearSwatchColor4"  Grid.Row="0" Grid.Column="2" Style="{DynamicResource ButtonClearSwatchColor}" Margin="5,20,5,5" HorizontalAlignment="Left"  Visibility="Hidden" Click="ClearSwatchColor_Click"/>
</StackPanel>

既然您已经有了所需ImageButton的名称,为什么还要使用FindName?为什么您不能通过名称直接访问它
ClearWatchColor1.xxx
您的代码看起来不错,应该可以使用。你是在UI呈现之前调用它吗?也许你没有很好地表达这个问题。附加组件定义IMGButton如果在构造函数中使用,请在初始化组件后尝试访问。
var swatchClearButton = swatchClearStackPanel.FindName("ClearSwatchColor1");