【问题标题】:Binding code-behind variable to text in textbox in main window将代码隐藏变量绑定到主窗口文本框中的文本
【发布时间】:2015-03-26 13:28:32
【问题描述】:

我在将文本框中输入的文本绑定到后面代码中的变量时遇到问题。

这是位于主窗口中的文本框的 xaml 代码:

<TextBox x:Name="Rotate1" Text="{Binding ElementName=this, Path=testvalue}" />

在主窗口后面的代码中:

private int testvalue { get; set;}

我知道如果是相反的方式,我必须在任何更改时更新源触发器,但不确定当它将变量更改为输入的文本时该怎么做。

【问题讨论】:

    标签: c# wpf data-binding textbox


    【解决方案1】:

    在代码中尝试:

    public partial class MainWindow : Window
    {
      public DependencyProperty TestValueProperty = DependencyProperty.Register("testvalue", typeof(int), typeof(MainWindow));
      public int testvalue
      {
        get { return (int)GetValue(TestValueProperty); }
        set
        {
          SetValue(TestValueProperty, value);
        }
      }
      public MainWindow()
      {
        InitializeComponent();
        testvalue = 6;
      }
    }
    

    在 XAML 中

    <Window x:Class="WpfApplication1.MainWindow"
        x:Name="thisForm"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <TextBox Text="{Binding ElementName=thisForm, Path=testvalue}" />
    </Window>
    

    UPD:哦!当然!删除 CS 和 XAML 代码中的标记

    【讨论】:

    • 感谢您的回复,但没有奏效。测试的时候,testvalue的值还是0。
    • 没有使用标签部分,但 dependencyProperty 正是我想要的。谢谢!
    猜你喜欢
    • 2015-10-21
    • 1970-01-01
    • 2015-09-22
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 2016-07-17
    相关资源
    最近更新 更多