【问题标题】:Change a textbox's text value on a UserControl from a Window in WPF从 WPF 中的窗口更改用户控件上的文本框的文本值
【发布时间】:2011-06-21 14:36:44
【问题描述】:

我有一个 UserControl(称为 Invoice),其文本框 (txtReferenceCode) 托管在 MainWindow 上的 TabControl (myTabControl) 中。我从 UserControl 调用一个窗口 (SearchWindow),其中包含库存项目列表。窗口需要返回一个字符串值到 UserControl 包含的文本框。我无法从窗口访问 UserControl 上的文本框,因此无法将字符串值从窗口传递给 text 属性。

UserControl 是作为新 tabItem 加载的实例(可能有许多作为 tabitems 内容打开的实例。)我只需要影响 UserControl 的当前 tabitem 实例。

例如:(SearchWindow 中的按钮单击事件)

Invoice.txtReferenceCode.Text = SearchWindow.txtReferenceCode.Text

我需要一个简单的、不复杂的解决方案,最好是在 VB 中(但我很乐意使用 C#)。

【问题讨论】:

    标签: wpf


    【解决方案1】:

    我明白了!我在这里为所有遇到此问题的人发布解决方案。

    XAML

    WPF 用户控件

    <UserControl x:Class="Invoice"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 mc:Ignorable="d"
                 d:DesignHeight="300" d:DesignWidth="300">
    
            <TextBox x:Name="txtReferenceCode" Width=100 />
    
    </UserControl>
    

    WPF 窗口

    <Window x:Class="SearchWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Height="300" Width="300">
    
        <TextBox X:Name="TextToChangeTextBox" Width=100 />
    
    </Window>
    

    代码隐藏

    将属性添加到您的窗口

    Class SearchWindow 
    
         Public ReadOnly Property TextValue
                 Get
                     Return TextToChangeTextBox.Text
                 End Get
         End Property
    
         ...
    
    End Class
    

    现在您可以使用窗口中的属性将字符串传递给 UserControl 上的 TextBox。

    Public Class Invoice
    
        Private Sub SetValueToTextBox
    
                Dim win As New SearchWindow
                win.ShowDialog()
    
                txtReferenceCode.Text = win.TextValue
    
        End Sub
    
        ...
    
    End Class
    

    *

    就是这样!简单!

    *

    【讨论】:

    • 谢谢..你的回答对我有帮助。
    【解决方案2】:

    有很多更好的方法可以做到这一点(即在两个窗口之间共享一个视图模型,并让绑定根据需要更新文本框)。

    但是,如果您坚持这样做,请尝试在您的文本框中添加一个公共修饰符,这样您就可以随意访问它。

    <TextBox Name="txtReferenceCode" x:FieldModifier="public"/>
    

    【讨论】:

    • MVVM 方式是这种情况下的最佳方式。两个控件共享相同的 DataContext (ViewModel)。
    • 嗨@viggity。谢谢回复。如果我添加字段修饰符,我将如何在代码隐藏中设置文本框的文本属性?
    猜你喜欢
    • 1970-01-01
    • 2014-01-26
    • 2011-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多