我尝试创建的UserControls
与Form Controls
中的常规Form
一样,或尽可能接近。
对于我的例子,我有一个UserControl
,里面有一个< TextBox>。我想给这个' UserControl'适用于TextBox
的所有函数和属性,以便它可以模仿TextBox
内的常规Form
。通过这种方式,我可以获取并设置其属性,并在Events
代码中调用Form
。
在我的Form1
中,我有一个常规的TextBox
,旁边是常规的Button
,ElementHost
文本框的UserControl
。
我想在顶部TextBox
输入一些字符串,点击我的添加Button
,并且必须从顶部TextBox
发送文字,传递到我内部的UserControl TextBox
ElementHost
因为我确定这是您在UserControl
中展示Form
的唯一方式!
这是我到目前为止所得到的。我不知道这是否是正确的做法,因为我对这一切都不熟悉。
UCTextbox.xaml - UserControl
<UserControl x:Class="UCTextbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:UCTextboxTest"
mc:Ignorable="d"
d:DesignHeight="50" d:DesignWidth="300">
<Grid>
<TextBox x:Name="txtBox" Text="{Binding Text}"/>
</Grid>
UCTextbox.xaml.vb - 返回代码
Public Class UCTextbox
Public Sub New()
' This call is required by the designer.'
InitializeComponent()
' Add any initialization after the InitializeComponent() call.'
Me.DataContext = Me
End Sub
'Get/Set the text value of my < TextBox > UserControl'
Private textValue As String
Public Property Text() As String
Get
Return textValue
End Get
Set(ByVal value As String)
textValue = value
End Set
End Property
' MORE PROPERTIES AND EVENTS WILL BE ADDED - KEEPING IT SIMPLE FOR NOW'
End Class
Form1布局
Form1 Class
Public Class Form1
'Create UserControl uc so that Button can reference it'
Dim uc As UCTextbox
Public Sub New()
' This call is required by the designer.'
InitializeComponent()
' Add any initialization after the InitializeComponent() call.'
'Tried creating UserControl-uc textbox and added it into ElementHost-hostTextbox here instead'
'Dim uc As UCTextbox = New UCTextbox()'
'hostTextbox.Child = uc'
'Me.Controls.Add(hostTextbox)'
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
uc = New UCTextbox()
hostTextbox.Child = uc
uc.Text = "Dog" 'Using uc function .Text only seem to work inside Form1_Load'
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
'This does not work here'
uc.Text = tbxTop.Text
hostTextbox.Child = uc 'Do I have to reapply the UserControl to the ElementHost each time I make a change to uc'
End Sub
End Class