Keep two textboxes synchronized in WPF

后端 未结 2 1930
谎友^
谎友^ 2020-12-17 18:19

I have two textboxes which I want to keep synchronized i.e. the content of both the textboxes should be exactly same. If one textbox changes the other textbox content should

相关标签:
2条回答
  • 2020-12-17 18:43

    Are you sure you want to bind one textbox to another textbox? By doing this changing the text value in the other textbox would not affect the other (unless each textbox binds to the other, which sounds like a ridiculous thing to do).

    The correct way to achieve this is to have both textboxes (or any number of textboxes, controls...etc) bind to a single Property. This property exists in the data-model and/or view-model.

    0 讨论(0)
  • 2020-12-17 19:08

    If that is what you want to do, WPF will let you do it:

    <Grid>
        <StackPanel>
            <TextBox x:Name="firstTextBox" Background="Silver" Text="{Binding Path=Text, ElementName=secondTextBox, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox>
            <TextBox x:Name="secondTextBox" Background="Gold" ></TextBox>
        </StackPanel>
    </Grid>
    

    The ElementName syntax is a very powerful addition to the basic approach of binding to properties in the DataContext. Many crazy things become possible.

    0 讨论(0)
提交回复
热议问题