C# 从WPF中的用户控件获取面板
我的主要观点是:C# 从WPF中的用户控件获取面板,c#,wpf,xaml,user-controls,findcontrol,C#,Wpf,Xaml,User Controls,Findcontrol,我的主要观点是: <Window ...> <WrapPanel Name="Container" Height="500" Width="1024" VerticalAlignment="Center"> <WrapPanel> <local:RequestListView /> </WrapPanel> </StackPanel> <
<Window ...>
<WrapPanel Name="Container" Height="500" Width="1024" VerticalAlignment="Center">
<WrapPanel>
<local:RequestListView />
</WrapPanel>
</StackPanel>
</Window>
但是返回null。就我所见,他不能“看”控制装置内部。如何获取这两个面板?这是可以帮助您的Helper类 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");
参考资料:
我希望这对您有所帮助:)因此,您正在尝试访问
StackPanel
内部的RequestFormViewModel
。你想用什么来达到目的?在WPF中,视图模型永远不应该直接访问视图,而应该将视图的属性公开给用户display@Gopichandar这一评论很有帮助。你是最棒的:)@Boo我正在用代码构建表单。也许我应该在xaml.cs类中这样做。你是这么说的吗?不!使用xaml构建表单(通常表单主要是静态的,如果是动态的,我们将在第二时间看到),然后,需要显示/编辑的属性必须绑定到viewModel
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");