【问题标题】:Accessing TextBox.Text from UserControl inside a ListBox从 ListBox 内的 UserControl 访问 TextBox.Text
【发布时间】:2014-01-21 22:41:48
【问题描述】:

我有一个需要更改页面上 TextBox 的 .text 的 UserControl。我的问题是我找不到从 UC 的代码隐藏中访问 TextBox 的方法。顺便说一句,我使用的是 Visual C++,而不是 C#。

基本上,UserControl 有一个 TextBox,当其中的文本发生更改时,我需要页面上 TextBox 中的文本进行更改。如果这有意义的话。

我已尝试将 Page TextBox 绑定到 UserControl TextBox,但我无法让任何一个 TextBox 找到另一个。我已经尝试在 UserControl 中#include Page .h,但这仍然无法让我访问 Page 上的 TextBox。我还研究了在 UserControl 上使用 Window::Current::Content ,但这似乎也无法让我访问页面文本框(除非我误解了它的工作原理)。

如果您需要我的任何代码,请告诉我,但现在它是一个更大项目的一部分,除非我删除一堆东西,否则没有任何意义,但是您将无法复制它并尝试运行它,所以我试图通过提供尽可能多的细节但保持简单来提出我的问题。我已经在互联网上搜索“XAML 将 TextBox 绑定到 UserControl”,虽然结果有限,但我已经完成了所有这些(我一直试图自己解决这个问题将近一个星期) .

【问题讨论】:

    标签: wpf xaml visual-c++ user-controls xaml-binding


    【解决方案1】:

    首先,我为您准备了三个链接,我真心希望您阅读链接页面。 MSDN 的第一个链接应该可以帮助您开始使用 WPF,因为很明显您还不知道如何使用它:

    Walkthrough: Getting Started with WPF

    第二个和第三个链接来自 StackOverflow 帮助中心,因为很明显您也没有阅读这些页面,它们将帮助您充分利用该网站(并更快地回答您的问题):

    How do I ask a good question?
    How to create a Minimal, Complete, Tested and Readable example

    现在解决您的问题...您可以简单地将DependencyProperty 添加到您的UserControl 并从控件内部和外部对其进行数据绑定。在后面的代码中:

    public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(
        "Value", typeof(string), typeof(MainWindow), new UIPropertyMetadata("Some text"));
    
    public string Value
    {
        get { return (string)GetValue(ValueProperty); }
        set { SetValue(ValueProperty, value); }
    }
    

    XAML 内部 UserControl:

    <TextBlock Text="{Binding Value, RelativeSource={RelativeSource AncestorType={x:Type 
        YourLocalPrefix:YourControlname}}}" />
    

    XAML 外部 UserControl:

    <YourLocalPrefix:YourControlname Value="{Binding SomePropertyOutsideControl}}}" />
    

    【讨论】:

      猜你喜欢
      • 2015-07-20
      • 1970-01-01
      • 2023-03-31
      • 2017-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多