I have a TabControl, with several TabItem. They have TextBox, which are booted into the same variable. I need that when switching between TabItem, these Text in the TextBox is erased.
1 answer
Connect the System.Windows.Interactivity library as written in this answer and familiarize yourself with this topic (question and answer).
Now everything is simple, ViewModel:
class MainVm : Vm { string text; public string Text { get => text; set => Set(ref text, value); } public DelegateCommand ClearTextCommand { get; } public MainVm() { ClearTextCommand = new DelegateCommand(_ => Text = ""); } } View:
<TabControl> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding ClearTextCommand}"/> </i:EventTrigger> </i:Interaction.Triggers> <TabItem Header="Tab 1"> <TextBox Text="{Binding Text}" VerticalAlignment="Top"> <i:Interaction.Behaviors> <c:TextBoxLostFocusUpdateBindingBehavior/> </i:Interaction.Behaviors> </TextBox> </TabItem> <TabItem Header="Tab 2"> <TextBox Text="{Binding Text}" VerticalAlignment="Top"> <i:Interaction.Behaviors> <c:TextBoxLostFocusUpdateBindingBehavior/> </i:Interaction.Behaviors> </TextBox> </TabItem> </TabControl> If the MVVM abbreviation means nothing to you, then you can simply subscribe to the PreviewLostKeyboardFocus your TextBox and update the binding in the subscriber (this is described in the above answer). Then subscribe to the SelectionChanged TabControl as well, and in the subscriber simply clear the property bound to TextBox am.
|