Binding code-behind variable to text in textbox in main window

回眸只為那壹抹淺笑 提交于 2019-12-25 01:56:03

问题


I'm having issues binding text entered in a textbox to a variable in code behind.

Here's the xaml code for the textbox located in the main window:

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

and in the code behind in main window:

private int testvalue { get; set;}

I know if it's the other way around I would have to update the source trigger on any change, but not sure what to do when it's changing variable to whatever the entered text is.


回答1:


try in code:

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;
  }
}

in 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: oh! of course! Remove Tag in CS and XAML code



来源:https://stackoverflow.com/questions/29257972/binding-code-behind-variable-to-text-in-textbox-in-main-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!