DataBind到WPF中的文本框

时间:2009-05-12 15:06:40

标签: c# wpf data-binding textbox

我对WPF中的数据绑定完全不熟悉,我正在尝试将对象属性绑定到文本框。我的目标是

public class TestObj
{
    private m_Limit;

    public string Limit
    {
       get 
        {
         return m_Limit;
        }
        set
        {
          m_Limit = value;
        }
    }

我的XAML看起来像

<Window x:Class="NECSHarness2.UpdateJobParameters"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tools="clr-namespace:ManagementObjects;assembly=Core"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
Title="Update Job Parameters" Height="320" Width="460">
<Grid>
    <TextBox Text ="{Binding Path = Limit, Mode = TwoWay}" Height="20" HorizontalAlignment="Right" Margin="0,48,29,0" Name="textBox3" VerticalAlignment="Top" Width="161" />
   </Grid>

现在,显然我没有在任何地方设置源,我很困惑。我得到了这个与listview一起工作,但现在我很难过。谢谢你的帮助。

4 个答案:

答案 0 :(得分:6)

您需要设置DataContext。在后面的代码中:

textBox3.DataContext = instanceOfTestObj;

或使用对象数据提供者

  <Window.Resources>
    <src:TestObj x:Key="theData" Limit="Wibble" />
  </Window.Resources>

  <TextBox Text="{Binding Source={StaticResource theData}..../>

对更深入的数据绑定有一个很好的介绍here

答案 1 :(得分:2)

如果未指定绑定的Source,RelativeSource或ElementName,则Binding使用控件的DataContext。 DataContext通过可视树从上层元素(例如Window)传递到下层元素(在您的情况下为TextBox)。

因此,WPF将在Window类中搜索Limit属性(因为您已将窗口的DataContext绑定到窗口本身)。

另外,您可能希望阅读有关WPF中DataBinding的基础知识:http://msdn.microsoft.com/en-us/library/ms750612.aspx

答案 2 :(得分:2)

对于TwoWay绑定工作,你的对象也必须实现INotifyPropertyChanged

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

答案 3 :(得分:1)

除非另有说明,否则绑定源始终是控件的DataContext。您必须将表单的DataContext设置为TestObj实例