VB.NET WPF如何为Form创建UserControls,其功能类似于Form中的常规Form控件

时间:2017-02-09 00:59:36

标签: wpf vb.net winforms xaml user-controls

编辑:我的上一个问题不是很好,所以我在这里改了。希望这个解释会更好!

我尝试创建的UserControlsForm Controls中的常规Form一样,或尽可能接近。

对于我的例子,我有一个UserControl,里面有一个< TextBox>。我想给这个' UserControl'适用于TextBox的所有函数和属性,以便它可以模仿TextBox内的常规Form。通过这种方式,我可以获取并设置其属性,并在Events代码中调用Form

在我的Form1中,我有一个常规的TextBox,旁边是常规的ButtonElementHost文本框的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 Layout

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

0 个答案:

没有答案