我有主视图:
<Window ...>
<WrapPanel Name="Container" Height="500" Width="1024" VerticalAlignment="Center">
<WrapPanel>
<local:RequestListView />
</WrapPanel>
</StackPanel>
</Window>
然后这个RequestListView是一个用户控件:
<UserControl x:Class="...RequestFormView">
<WrapPanel Name="Teste" Margin="20" Width="1000">
<StackPanel Name="LeftPanel" Width="500">
<WrapPanel>
<Label Content="Nome do Pedido"/>
<TextBox MinWidth="200" Text="{Binding Request.descRequest}"></TextBox>
</WrapPanel>
<StackPanel Name="LeftContainer">
</StackPanel>
</StackPanel>
<StackPanel Name="RigthPanel" Width="500">
<Label Content="Os campos marcados com * são obrigatórios."></Label>
<Button Width="75" Height="26" Content="Save"/>
<Button Width="75" Height="26" Content="Cancel"/>
</StackPanel>
<StackPanel Name="RightContainer">
</StackPanel>
</WrapPanel>
</UserControl>
现在在我的RequestFormViewModel上,我想访问“LeftContainer”和“RightContainer”面板。我在尝试:
StackPanel rightPanel = (StackPanel)Application.Current.MainWindow.FindName("RightContainer");~
但是返回null。据我所见,他不能“看”控制内部。我怎样才能获得这两个面板?
答案 0 :(得分:0)
这是可以帮助你的助手类。
<强> UIHelper.cs 强>
public static class UIHelper
{
public static DependencyObject FindChild(DependencyObject parent, string name)
{
// confirm parent and name are valid.
if (parent == null || string.IsNullOrEmpty(name)) return null;
if (parent is FrameworkElement && (parent as FrameworkElement).Name == name) return parent;
DependencyObject result = null;
if (parent is FrameworkElement) (parent as FrameworkElement).ApplyTemplate();
int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < childrenCount; i++)
{
var child = VisualTreeHelper.GetChild(parent, i);
result = FindChild(child, name);
if (result != null) break;
}
return result;
}
}
像这样称呼
StackPanel foundStackPanel = (StackPanel) UIHelper.FindChild(Application.Current.MainWindow, "RightContainer");
参考: Find control in the visual tree
我希望这对你有帮助:))