【发布时间】:2010-11-20 15:02:54
【问题描述】:
具有 TabControl 的 Silverlight 3 应用程序使用 IValueConverter 绑定到 ObservableCollection。在应用程序启动时初始化绑定工作(调用转换器)。对绑定集合的更改、Clear() 或 Add() 不会反映在 TabControl... 转换器未调用。
注意:绑定的 ListBox 反映了对绑定集合的更改,而 TabControl 没有。
想法?
/jhd
XAML 绑定...
<UserControl.Resources>
<local:ViewModel x:Key="TheViewModel"/>
<local:TabConverter x:Key="TabConverter" />
</UserControl.Resources>
<StackPanel DataContext="{StaticResource TheViewModel}">
<ListBox ItemsSource="{Binding Classnames}" />
<controls:TabControl x:Name="TheTabControl"
ItemsSource="{Binding Classnames, Converter={StaticResource TabConverter}, ConverterParameter=SomeParameter}"/>
<Button Click="Button_Click" Content="Change ObservableCollection" />
</StackPanel>
ViewModel...
namespace DatabindingSpike
{
public class ViewModel
{
private ObservableCollection<string> _classnames = new ObservableCollection<string>();
public ViewModel()
{
_classnames.Add("default 1 of 2");
_classnames.Add("default 2 of 2");
}
public ObservableCollection<string> Classnames
{
get { return _classnames; }
set { _classnames = value; }
}
}
}
转换器(为了完整性)...
namespace DatabindingSpike
{
public class TabConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var source = value as ObservableCollection<string>;
if (source == null)
return null;
var param = parameter as string;
if (string.IsNullOrEmpty(param) || param != "SomeParameter")
throw new NotImplementedException("Null or unknow parameter pasased to the tab converter");
var tabItems = new List<TabItem>();
foreach (string classname in source)
{
var tabItem = new TabItem
{
Header = classname,
Content = new Button {Content = classname}
};
tabItems.Add(tabItem);
}
return tabItems;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
【问题讨论】:
-
默认模式是一次性的吗?将尝试明确设置模式。 /jhd
-
试过显式模式=OneWay,没有乐趣。我将使用 CollectionChanged 事件并重新设置 TabControl.ItemsSource,直到找到更好的方法。 /jhd
-
我创建了扩展选项卡控件,它可以与 ObservableCollection 类一起正常工作。 vortexwolf.wordpress.com/2011/04/09/…
标签: silverlight data-binding tabcontrol observablecollection