如何将绑定属性更正为文本框?

时间:2011-10-08 14:11:44

标签: c# windows-phone-7 binding textbox inotifypropertychanged

我在mainpage.xaml

中编写了这些代码
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <StackPanel>
            <TextBox x:Name="xxx" Text="{Binding Test}" TextChanged="xxx_TextChanged" />
            <Button x:Name="click" Click="click_Click" Content="click" />
        </StackPanel>
    </Grid>

这些在mainpage.xaml.cs

  private string test;
    public string Test
    {
        get { return test; }
        set 
        {
            if (test != value)
            {
                test = value;
                OnPropertyChanged("Test");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public  void OnPropertyChanged(string PropertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
        }
    }

    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    private void xxx_TextChanged(object sender, TextChangedEventArgs e)
    {
        Debug.WriteLine(Test);
        Debug.WriteLine(test);
    }

但是测试没有绑定到文本框,当我将smth写入文本框时测试没有改变。 我做错了什么以及如何纠正?

1 个答案:

答案 0 :(得分:1)

尝试将BindingMode设置为TwoWay:

Text="{Binding Test, Mode=TwoWay}"

我注意到的另一件事是,你的工作绑定需要设置DataContext,但你不能在你的例子中这样做。一种方法是这样的:

public MainPage()
{
    InitializeComponent();
    ContentPanel.DataContext = this;
}

如果首选Xaml,您可以使用RelativeSource属性绑定到Xaml中的页面,而无需设置DataContext:

Text="{Binding RelativeSource={RelativeSource FindAncestor,
                               AncestorType={x:Type Window}}, //or Page
       Path=Test, Mode=TwoWay}"

另一件事,Test将不会在您在TextBox中键入的每个字符之后设置,而是在用户完成文本编辑后设置,例如将活动控件切换到下一个。

相关问题