【问题标题】:How to bind the text in a textbox of a usercontrol into a textblock?如何将用户控件文本框中的文本绑定到文本块中?
【发布时间】:2012-11-08 03:27:32
【问题描述】:

我创建了一个用户控件文本框,我想将文本块绑定到我在用户控件的文本框中键入的内容。我尝试了一些代码,但它不起作用。有谁能教我?谢谢

我的用户控件文本框:

<Grid  Background="Silver" Style="{StaticResource EntryFieldStyle}"  Width="175" Height="25" Margin="0" >          
    <TextBox Name="watermarkTextBox" Background="Green"   />    
</Grid>

我的 xaml 代码:

<StackPanel Orientation="Horizontal">
      <UserControls:WatermarkTextBox x:Name="usernameArea"/>
      <TextBlock Text="{Binding ElementName=usernameArea Path=watermarkTextBox.Text}"  FontSize="13" Foreground="White"/> 
</StackPanel>

【问题讨论】:

    标签: c# wpf data-binding user-controls


    【解决方案1】:

    Edit2:一种方法是使用依赖属性以及实现 INotifyPropertyChanged。

    每次文本框的文本发生更改时,我们都会触发一个 PropertyChangedEvent。 Window 窗口将通过访问 WatermarkTextBox 的 WatermarkText 依赖属性来订阅此事件。

    它的外观如下:


    WatermarkTextbox.xaml:

    <TextBox Name="watermarkTextBox" ...
             TextChanged="watermarkTextBox_TextChanged"/>
    

    WatermarkTextbox.xaml.cs:

    public partial class WatermarkTextBox : UserControl, INotifyPropertyChanged
    {
        ...
        public static readonly DependencyProperty WatermarkTextProperty =
            DependencyProperty.Register("WatermarkTextProperty", typeof(String),
            typeof(WatermarkTextBox), new PropertyMetadata(null));
    
        public String WatermarkText
        {
            get { return watermarkTextBox.Text; }
            set { OnPropertyChanged("WatermarkText"); }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string name)
        {
                PropertyChangedEventHandler handler = PropertyChanged;
                if (handler != null)
                {
                    handler(this, new PropertyChangedEventArgs(name));
                }
         }
         private void watermarkTextBox_TextChanged(object sender, TextChangedEventArgs e)
         {
               WatermarkText = this.watermarkTextBox.Text;
         }
    
    }
    

    [主窗口].xaml:

          <TextBlock Text="{Binding ElementName=usernameArea Path=WatermarkText}" .../> 
    

    添加dependency property 实质上允许您在用户控件中公开值以在 XAML 中进行修改(以及一般的绑定)。


    您可能还想将TextBlockForeground(文本颜色)属性更改为比白色更深的颜色,因为默认情况下Background 是白色的。

    【讨论】:

    • 你把前景改成黑色了吗?
    • @0070 对不起,忘了依赖属性的东西。我用答案更新了解决方案。这对我有用。
    • 哦,还是不行……我的背景是黑色的,所以字体是可见的。你能解释一下在dependencyProperty.register的每个参数中应该放什么参数吗?
    • @0070 Gahh,再次抱歉。这就是我试图过快地编写代码所得到的。我在想绑定是相反的。我现在将发布一个可行的解决方案。
    • @0070 应该可以。很抱歉所有的编辑。希望这会有所帮助!
    猜你喜欢
    • 2012-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    • 2014-01-26
    • 1970-01-01
    • 2014-02-19
    • 1970-01-01
    相关资源
    最近更新 更多