如何绑定的TabControl? [英] How bind TabControl?

查看:138
本文介绍了如何绑定的TabControl?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XAML

 <控制:TabControl的X:名称=tabControlRoomGrid.Row =1Grid.Column =1D:LayoutOverrides =宽度,高度的ItemsSource ={结合}> 
<控制:TabControl.ItemTemplate>
<&DataTemplate的GT;
<控制:TabItem的标题={结合NAME}>
< StackPanel的保证金=10方向=横向>

< / StackPanel的>
< /控制:TabItem的>
< / DataTemplate中>
< /控制:TabControl.ItemTemplate>
< /控件:TabControl的>

和代码



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

当我打开这个网页,再有就是所有的元素,但第二个后,我只看到白色屏幕



错误:




负荷运转失败查询
'GetRoom。无法投
型'Web.Room对象键入
'System.Windows.Controls.TabItem/



解决方案

创建转换器

 公共类SourceToTabItemsConverter:的IValueConverter 
{
公共对象转换(对象的值,类型TARGETTYPE,对象参数,System.Globalization.CultureInfo文化)
{

{
无功源=(IEnumerable的)值;
如果(来源!= NULL)
{
VAR的ControlTemplate =(控件模板)参数;

变种的TabItems =新的List<&TabItem的GT;();

的foreach(在源对象的项目)
{
的PropertyInfo [] = propertyInfos item.GetType()的GetProperties()。

//тутмывыбираем,тополекотороебудет头。 Выдолжнысамивводитьэтозначение。
变种的PropertyInfo = propertyInfos.First(X => x.Name ==名称);

字符串HEADERTEXT = NULL;
如果(的PropertyInfo!= NULL)
{
对象propValue = propertyInfo.GetValue(项目,NULL);
HEADERTEXT =(propValue ??的String.Empty)的ToString();
}

变种TabItem的=新TabItem的
{
的DataContext =项目,
标题= HEADERTEXT,
含量=
的ControlTemplate == NULL
?项目
:新ContentControl中{模板=控件模板}
};

tabItems.Add(TabItem的);
}

返回的TabItems;
}
返回NULL;
}
赶上(例外)
{
返回NULL;
}
}

///<总结>
/// ConvertBack方法不支持
///< /总结>
公共对象ConvertBack(对象的值,类型TARGETTYPE,对象参数,System.Globalization.CultureInfo文化)
{
抛出新NotSupportedException异常(不支持ConvertBack法);
}

创建控件模板:

 <控件模板X:键=MyTabItemContentTemplate> 
<&StackPanel的GT;
< TextBlock的文本={绑定路径=名}/>
< / StackPanel的>
< /控件模板>

和约束力转换,控件模板

 <控制:TabControl的X:名称=TabControl的
的ItemsSource ={绑定的ElementName = TabControl的,
路径=的DataContext,
转换器= {StaticResource的ConverterCollectionToTabItems }
ConverterParameter = {StaticResource的MyTabItemContentTemplate}}>
< /控件:TabControl的>



从博客的绑定的tabcontrol


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>

and code

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

when I open this page, then there is all the elements, but a second later I see only a white screen

error:

load operation failed for query 'GetRoom'. Unable to cast object of type 'Web.Room' to type 'System.Windows.Controls.TabItem'/'

解决方案

Create converter

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");
        }

Create ControlTemplate:

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

And binding convert, controltemplate

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

taken from the blog binding-tabcontrol

这篇关于如何绑定的TabControl?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆