我如何通过它的名称引用GUI元素作为所有元素的字符串,甚至是标签项内的网格中的元素。 现在我有了这段代码:
Module VisualExtensions
<System.Runtime.CompilerServices.Extension>
Public Iterator Function GetVisualChildren(Of T As Visual)(parent As DependencyObject) As IEnumerable(Of T)
Dim child As T = Nothing
Dim numVisuals As Integer = VisualTreeHelper.GetChildrenCount(parent)
For i As Integer = 0 To numVisuals - 1
Dim v As Visual = DirectCast(VisualTreeHelper.GetChild(parent, i), Visual)
child = TryCast(v, T)
If v IsNot Nothing Then
For Each item In GetVisualChildren(Of T)(v)
Yield item
Next
End If
If child IsNot Nothing Then
Yield child
End If
Next
End Function
End Module
这段代码称之为:
Try
For Each s In output
Dim nameOfControl = s
Dim window = Windows.Application.Current.Windows(0)
Dim visuals = GetVisualChildren(Of FrameworkElement)(window)
Dim child = visuals.OfType(Of FrameworkElement)()
Dim match = child.FirstOrDefault(Function(x) x.Name = nameOfControl)
match.Visibility = Visibility.Collapsed
Next
Catch ex As NullReferenceException
Finally
End Try
如果 s 是&#34; veleprodajaTab&#34;它运行良好(代码折叠该选项卡)和该选项卡的xml是:
<TabItem x:FieldModifier="public" x:Name="veleprodajaTab" Header="Maloprodaja" FontSize="10" VerticalAlignment="Bottom">
但如果 s 是&#34; buttonRefresh&#34;它不起作用,它不能引用该对象。我在调试中遇到nullreferenceexception 孩子 Nothing
代码&#34; buttonRefresh&#34; (围着它的网格):
<TabItem x:FieldModifier="public" x:Name="maloprodajaTab"...
<Grid x:FieldModifier="public" x:Name="maloprodajaTabGrid"...
<Grid x:FieldModifier="public" x:Name="gridFckp"
<Button x:FieldModifier="public" x:Name="buttonRefresh" Content="Refresh" HorizontalAlignment="Left" Margin="276,6,0,0" VerticalAlignment="Top" Width="75" Grid.ColumnSpan="2"/>
</grid>
</grid>
我似乎无法引用** TabItem **
内的任何内容如果我尝试设置window.buttonRefresh.Visibility = Visibility.Collapsed代码有效,但在网格中引用 childs 时出现问题
答案 0 :(得分:1)
由于TabControl已虚拟化,因此无法实现。您需要在Visual Tree中导航,向其传递所需元素的名称。看看这里: Find WPF controls by name or type
所以你可以这样做:
set terminal postscript enhanced color
set output 'test.ps'
set xlabel 'x'
set ylabel 'y'
set title 'Top 1'
set key box vertical width 2 height 1 maxcols 1 spacing 3
set xr [0:pi]
set xtics nomirror
set ytics nomirror
plot \
sin(x) w l lw 3 lc rgb 'red' t '{/Symbol y}', \
cos(x) w l lw 3 lc rgb 'blue' t '@{/Symbol ~&{y}{-1.0&{.}}}{/Symbol ~y{0.8.}}@{/Symbol &{y}}'
并称之为:
private T FindChildByname<T>(DependencyObject parent, string name) where T : FrameworkElement
{
T child = default(T);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
{
var ch = VisualTreeHelper.GetChild(parent, i);
child = ch as T;
if (child != null && child.Name == name)
break;
else
child = FindChildByname<T>(ch, name);
if (child != null) break;
}
return child;
}