如何绑定TabControl

本文关键字:TabControl 绑定 何绑定 | 更新日期: 2023-09-27 17:58:01

xaml

<controls:TabControl x:Name="tabControlRoom" Grid.Row="1" Grid.Column="1" d:LayoutOverrides="Width, Height" ItemsSource="{Binding}" >
            <controls:TabControl.ItemTemplate>
                <DataTemplate>
                    <controls:TabItem Header="{Binding name}">
                        <StackPanel Margin="10" Orientation="Horizontal">
                        </StackPanel>
                    </controls:TabItem>
                </DataTemplate>
            </controls:TabControl.ItemTemplate>
        </controls:TabControl>

并编码

m_roomContext.Load(m_roomContext.GetRoomQuery());
                tabControlRoom.DataContext = m_roomContext.Rooms;

当我打开这个页面时,里面有所有的元素,但一秒钟后我只看到一个白色的屏幕

错误:

查询的加载操作失败"GetRoom"。无法强制转换的对象键入"Web"。房间'按类型’系统。Windows。控件。选项卡项"/"

如何绑定TabControl

创建转换器

public class SourceToTabItemsConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            try
            {
                var source = (IEnumerable)value;
                if (source != null)
                {
                    var controlTemplate = (ControlTemplate)parameter;
                    var tabItems = new List<TabItem>();
                    foreach (object item in source)
                    {
                        PropertyInfo[] propertyInfos = item.GetType().GetProperties();
                        //тут мы выбираем, то поле которое будет Header. Вы должны сами вводить это значение.
                        var propertyInfo = propertyInfos.First(x => x.Name == "name");
                        string headerText = null;
                        if (propertyInfo != null)
                        {
                            object propValue = propertyInfo.GetValue(item, null);
                            headerText = (propValue ?? string.Empty).ToString();
                        }
                        var tabItem = new TabItem
                                          {
                                              DataContext = item,
                                              Header = headerText,
                                              Content =
                                                  controlTemplate == null
                                                      ? item
                                                      : new ContentControl { Template = controlTemplate }
                                          };
                        tabItems.Add(tabItem);
                    }
                    return tabItems;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// ConvertBack method is not supported
        /// </summary>
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException("ConvertBack method is not supported");
        }

创建控制模板:

<ControlTemplate x:Key="MyTabItemContentTemplate">
            <StackPanel>
                <TextBlock Text="{Binding Path=name}" />
            </StackPanel>
        </ControlTemplate>

和绑定转换,控制模板

<controls:TabControl  x:Name="tabControl"
        ItemsSource="{Binding ElementName=tabControl, 
                              Path=DataContext, 
                              Converter={StaticResource ConverterCollectionToTabItems}, 
                              ConverterParameter={StaticResource MyTabItemContentTemplate}}">
        </controls:TabControl>

取自博客绑定选项卡控制

绑定TabControl时,需要完成两件事,一件是TabItem的头内容,另一件是所选TabItem的内容,后者通常是另一个用户控件。

我过去解决这个问题的方法是将TabControl的ItemsSource绑定到视图模型的集合,并提供两个数据模板,一个为TabItem提供标头内容,另一个为映射到视图的选定TabItem提供内容。

<Window.Resources>
    <DataTemplate x:Key="ItemTemplate">
        <TextBlock Text="{Binding Title}" />
    </DataTemplate>
    <DataTemplate x:Key="ContentTemplate">
        <local:SampleView />
    </DataTemplate>
</Window.Resources>
<Grid>
    <TabControl 
        ItemsSource="{Binding SampleViewModels}" 
        ItemTemplate="{StaticResource ItemTemplate}"
        ContentTemplate="{StaticResource ContentTemplate}"
        SelectedIndex="0"
        />
</Grid>