0

I have a window which contains a a TabControl with 2 TabItems inside it. Inside the second tab, there is a TextBox with a binding to a string property inside my view model. I want to be able to clear this property (or the TextBox since it is bound it will will by association, clear the property) whenever the user clicks on a different tab (and also if the user closes the window). I'm hoping I can achieve this with only the XAML since I am trying to follow the MVVM pattern (so no code behind and my view model shouldn't know of the TabControl or TextBox that is in my view).

I have tried a few different things and can't quite get it working and while I'm getting better at WPF, I'm still fairly new to it. Inside my tabs I also have ListViews and ComboBoxes, which from my understanding will bubble the SelectionChanged event (same as when the tab selection is changed) so I should probably stay away from that. Any help would be appreciated.

Here was one of my attempts (snippet showing the gist):

<TabControl>
<TabItem>
    ...Stuff in first tab goes here
</TabItem>

<TabItem Header="Rules">
    <TabItem.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{IsSelected}" Value="True">
                    <Setter TargetName="UserBox" Property="Text" Value="" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TabItem.Style>


    <GroupBox>
        <UniformGrid>
            <ListView ItemsSource="{Binding Source={StaticResource rulesViewModel}, Path=RulesList}">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Header="Rules"/>
                    </GridView>
                </ListView.View>
            </ListView>

            <DockPanel>
                <TextBox Name="UserBox" Text="{Binding Source={StaticResource rulesViewModel}, Path=User}" />
            </DockPanel>
        </UniformGrid>
    </GroupBox>
</TabItem>

I'm pretty sure the line that reads Binding="{IsSelected}" is wrong. But I'm not sure how to target the correct property. Any ideas?

4

2 回答 2

0

我认为最好的方法是使用交互库来捕获SelectionChanged属性并更改属性。它看起来像这样:

<TabControl>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <ei:ChangePropertyAction TargetObject="{Binding Path=Path.To.ViewModel}" PropertyName="MyProperty" Value="" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TabControl>

您还可以选择更改 TextBox 的值 - 在这种情况下,您需要将ChangePropertyAction对象修改为如下所示:

<ei:ChangePropertyAction TargetName="UserBox" PropertyName="Text" Value="" />
于 2013-07-10T21:23:26.563 回答
0

您需要设置要在其他选项卡单击时清除其内容的选项卡的 SelectedIndex = -1。

SelectedIndex = -1 是默认选项卡,所以基本上我们将此选项卡设为默认选项卡。现在条件变成了

如果选择索引!= -1,应清除文本或在应用程序关闭时,应清除文本

我已经为您提供了逻辑,现在可以编写代码了:)

于 2013-07-11T04:10:16.370 回答