我有一个用户控件,我需要从另一个窗口访问该用户控件上的标签..例如...只需更改标签的文本。例如..用户控件上的访问控制
Usercontrol.label1.content = "Got it"
我可以在主窗口做访问任何控制以下内容:
Public main As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
如何做到这一点在WPF用户控件?
我有一个用户控件,我需要从另一个窗口访问该用户控件上的标签..例如...只需更改标签的文本。例如..用户控件上的访问控制
Usercontrol.label1.content = "Got it"
我可以在主窗口做访问任何控制以下内容:
Public main As MainWindow = DirectCast(Application.Current.MainWindow, MainWindow)
如何做到这一点在WPF用户控件?
要访问主窗口:
Dim Main = TryCast(Application.Current.MainWindow, MainWindow);
如果你的用户控件定义静态这样的:
<local:UserControl1 x:Name="uc" />
你可以使用它的名字一样:Main.uc.label1.Text = "Hello World"
如果你的用户控件动态添加到一个容器中,尝试以下操作:
如果您的用户控件位于边框中:
Dim control = Main.MyBorder.Child as MyUserControl
control.label1.Text = "Hello World"
如果在你的容器的多个用户控件,如(StackPanel中/表格/ Wrappanel等):
Dim controls = Main.MyStackPanel.Childern.OfType(Of MyUserControl)()
For Each control In controls
control.label1.Text = "Hello World"
Next
即使你可以通过检查它的变量来得到你想要的确切用户控件!
Dim control = Main.MyStackPanel.Childern.OfType(Of MyUserControl)().Where(Function(x) x.label1.Text = "myLabel").FirstOrDefault()
//You can access any variable that exists in your UserControl by 'x'
control.label1.Text = "Hello World"
一旦您获得了UserControl
所在的窗口的引用,就可以使用此引用访问它。
因此,如果UserControl
例如在一个名为Window1
窗口中定义,这里是如何,你可以从另一个窗口访问:
Dim window1 As Window1 = Application.Current.Windows.OfType(Of Window1).FirstOrDefault()
window1.uc.label1.Text = "1"
这当然假定有一个Window1
开上可见屏幕和您在窗口的XAML标记给出的UserControl
元素的x:Name
:
<local:UserControl1 x:Name="uc" />
您不需要“访问”任何地方的任何标签。使用视图模型并在XAML中适当地绑定它的属性。 –