我想提出一个简单的解决方案。
<TabControl ItemsSource="{Binding Items}">
<TabControl.Resources>
<DataTemplate DataType="{x:Type local:AccountViewModel}">
<local:AccountUserControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type local:AddressViewModel}">
<local:AddressUserControl/>
</DataTemplate>
</TabControl.Resources>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Label}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentControl Content="{Binding }"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
MainViewModel 是
public class MainViewModel: ViewModelBase
{
List<ItemViewModel> _items = new List<ItemViewModel>();
public List<ItemViewModel> Items
{
get { return _items; }
set { _items = value; OnPropertyChanged(nameof(Items)); }
}
public MainViewModel()
{
Items= [new AddressViewModel(),new AccountViewModel()];
}
}
ItemViewModel 是:
public class ItemViewModel : ViewModelBase
{
string _label = "";
public string Label
{
get { return _label; }
set { _label = value; OnPropertyChanged(nameof(Label)); }
}
}
AccountViewModel 是:
public class AccountViewModel : ItemViewModel
{
string _AccountNumber = "";
public string AccountNumber
{
get { return _AccountNumber; }
set { _AccountNumber = value; OnPropertyChanged(nameof(AccountNumber)); }
}
string _bank = "";
public string Bank
{
get { return _bank; }
set { _bank = value; OnPropertyChanged(nameof(Bank)); }
}
public AccountViewModel()
{
Label = "Account";
Bank = "People Bank";
AccountNumber = "791800";
}
}
AddressViewModel 是:
public class AddressViewModel : ItemViewModel
{
string _address = "";
public string Address
{
get { return _address; }
set { _address = value;OnPropertyChanged(nameof(Address)); }
}
string _city = "";
public string City
{
get { return _city; }
set { _city = value; OnPropertyChanged(nameof(City)); }
}
public AddressViewModel()
{
Label = "Address";
Address = "1349 BellField Way";
City = "Belleview";
}
}
AccountUserControl 是:
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding AccountNumber}"/>
<TextBlock Text="{Binding Bank}"/>
</StackPanel>
</Grid>
AddressUserControl 是:
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Text="{Binding City}"/>
<TextBlock Text="{Binding Address}"/>
</StackPanel>
</Grid>