c# - 为什么我的数据绑定(bind) TabControl 看起来不像我的非数据绑定(bind) TabControl?

标签 c# wpf xaml data-binding tabcontrol

我的非数据绑定(bind) TabControl 看起来不错:

alt text http://tanguay.info/web/external/tabControlPlain.png

<TabControl Width="225" Height="150">
    <TabItem Header="One">
        <TextBlock Margin="10" Text="This is the text block"/>
    </TabItem>
    <TabItem Header="Two"/>
    <TabItem Header="Three"/>
    <TabItem Header="Four"/>
</TabControl>

但是我的数据绑定(bind) TabControl 看起来像这样:

alt text http://tanguay.info/web/external/tabBound.png

<Window.Resources>
    <DataTemplate x:Key="TheTabControl">
        <TabItem Header="{Binding Title}">
            <TextBlock Text="{Binding Description}" Margin="10"/>
        </TabItem>
    </DataTemplate>
</Window.Resources>

<TabControl Width="225" Height="150" ItemsSource="{Binding AreaNames}"
            ItemTemplate="{StaticResource TheTabControl}">
</TabControl>

public MainViewModel()
{
    AreaNames.Add(new Area { Title = "Area1", Description = "this is the description for area 1" });
    AreaNames.Add(new Area { Title = "Area2", Description = "this is the description for area 2" });
    AreaNames.Add(new Area { Title = "Area3", Description = "this is the description for area 3" });
}

#region ViewModelProperty: AreaNames
private ObservableCollection<Area> _areaNames = new ObservableCollection<Area>();
public ObservableCollection<Area> AreaNames
{
    get
    {
        return _areaNames;
    }

    set
    {
        _areaNames = value;
        OnPropertyChanged("AreaNames");
    }
}
#endregion

我必须更改什么才能使我的数据绑定(bind)选项卡控件看起来像常规的非数据绑定(bind)选项卡控件?

最佳答案

TabControl 使用两个不同的模板来定义其结构。 ItemTemplate 用于标题(“选项卡”),ContentTemplate 用于每个选项卡下显示的内容。

此 XAML 看起来更像您的第一个屏幕截图:

<Window.Resources>
    <DataTemplate x:Key="TabHeaderTemplate">
        <TextBlock Text="{Binding Title}"/>
    </DataTemplate>

    <DataTemplate x:Key="TabItemTemplate">
        <TextBlock Text="{Binding Description}" Margin="10"/>
    </DataTemplate>
</Window.Resources>

<TabControl Width="225" Height="150" 
            ItemsSource="{Binding AreaNames}"            
            ContentTemplate="{StaticResource TabItemTemplate}"         
            ItemTemplate="{StaticResource TabHeaderTemplate}" />

关于c# - 为什么我的数据绑定(bind) TabControl 看起来不像我的非数据绑定(bind) TabControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/984472/

相关文章:

wpf - DataGridComboBoxColumn 中的 "An inline collection of ComboBoxItem"

xaml - 更改 Xamarin.Forms 中的文本颜色

c# - 如何在 AX 查询服务中格式化 DateTime 比较值

c# - 在 Azure Functions 中使用类

c# - OleDbDataReader 如何读取数字类型?

c# - 我如何创建特定编号的 ListView。 WPF 中的列数?

wpf - MVVM - View 真的需要有一个默认的构造函数吗?

algorithm - 按元素数量设置行和列定义

c# - 在 C# 中运行命令行参数

c# - 如何更新远程 ms sql server 上的数据库(EF 代码优先)