开发者

How to correct bind property to textbox?

开发者 https://www.devze.com 2023-04-11 20:47 出处:网络
I write these code in mainpage.xaml <Grid x:Name=\"ContentPanel\" Grid.Row=\"1\" Margin=\"12,0,12,0\">

I write these code in 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>

And these in mainpage.xaml.cs

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

    public event PropertyChanged开发者_如何学JAVAEventHandler 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);
    }

But Test isn't binded to textbox, when I write smth to textbox Test isn't changed. What I doing wrong and how to correct that ?


Try setting BindingMode to TwoWay:

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

The other thing I've noticed, is that your binding to work need DataContext to be set, but you don't do that in your example. One way to do this would be something like this:

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

If staying in Xaml is preferred, you can use RelativeSource property to bind to your page in Xaml, without setting DataContext:

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

Another thing, Test will be set not after every character you type in your TextBox, but after user will finish editing text, for example by switching active control to next one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号