Different updates in two way binding

BitSmithy 1,811 Reputation points
2023-09-05T14:27:00.8033333+00:00

Hello,

I want to bind Rectangle.WidthProperty to TextBox.

But ... I want to have such behavior.

If I type width value in TextBox it should to be transported to Rectange Explit

If I change widt in Rectangle code behind, it should be transported to TextBox on PropertyChanged.

Is there possible to do such behavior in UWP?

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Junjie Zhu - MSFT 15,601 Reputation points Microsoft Vendor
    2023-09-06T02:21:51.2266667+00:00

    Hello @BitSmithy ,

    Welcome to Microsoft Q&A!

    It is recommended that you use element binding Text="{Binding ElementName=rectangleTest, Path=Width}", and change the Rectangle.WidthProperty in event TextChanged.

    <StackPanel>
        <Rectangle x:Name="rectangleTest" Height="200" Width="100" Fill="Red"/>
        <TextBox x:Name="textboxTest" Text="{Binding ElementName=rectangleTest, Path=Width}" TextChanged="textboxTest_TextChanged" Height="50" Width="100"/>
        <Button Content="change the width" Click="Button_Click" />
    </StackPanel>
    
    private void textboxTest_TextChanged(object sender, TextChangedEventArgs e)
    {
        double dbWidth;
    
        if (double.TryParse(textboxTest.Text, out dbWidth))
        {
            if (dbWidth >= 0)
            {
                rectangleTest.Width = dbWidth;
            }
        }
    }
    
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        rectangleTest.Width = 300;
    }
    

    Thank you.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful