Wpf Tab控件DataBinding

时间:2014-05-13 18:36:03

标签: c# wpf data-binding

我正在使用wpf标签控件,我需要检测标签更改,并且还能够以编程方式更改标签,我想在两种情况下都做不同的事情。我该怎么做?

<TabControl ItemsSource="{Binding Path=ResultsCollection}" SelectedItem="{Binding SelectedItem}">
</TabControl>

我的视图模型中的属性

public ResultObject SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            if (SelectedItem != null && SelectedItem.Equals(value)) 
                return;

            _selectedItem = value;
            OnPropertyChanged(() => SelectedItem);
        }
    }

2 个答案:

答案 0 :(得分:0)

尝试绑定到SelectedIndex;

SelectedIndex="{Binding SelectedIndex}"

<强> XAML:

<Window x:Class="MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
    <Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Margin="56,272,0,0" Click="Button_Click"/>
    <TabControl HorizontalAlignment="Left" Height="231" VerticalAlignment="Top" Width="507" SelectedIndex="{Binding MyTabIndex, Mode=TwoWay}">
        <TabItem Header="TabItem">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
        <TabItem Header="TabItem">
            <Grid Background="#FFE5E5E5"/>
        </TabItem>
    </TabControl>

</Grid>
</Window>

<强> VB:

Imports System.ComponentModel

Class MainWindow : Implements INotifyPropertyChanged

Private _MyTabIndex As Integer

Public Property MyTabIndex As Integer
    Get
        Return _MyTabIndex
    End Get
    Set(value As Integer)

        If value <> _MyTabIndex Then

            _MyTabIndex = value

            RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("MyTabIndex"))

        End If

    End Set
End Property


Private Sub Button_Click(sender As Object, e As RoutedEventArgs)

    MyTabIndex += 1


End Sub

Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements INotifyPropertyChanged.PropertyChanged

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    Me.DataContext = Me


End Sub
End Class

答案 1 :(得分:0)

您已经正确绑定到SelectedItem。由于您的模型已经可以使用,因此当您需要更改时,为什么不在那里更改所选项目。即:

SelectedItem = MyNewTabToSwitchTo;

可能还需要将绑定上的模式设置为twoway。