在我的WPF應用程序中,我想在包含TabControl的可重用UserControl內動態創建TabItems。動態創建帶有MultiBinding和RelativeSource的TabItems - > UnsetValue
TabControl的ItemsSource通過標準DataBinding綁定到ObservableCollection實例。
我創建了這樣的Tab項目AFTERInitializeComponent()
已被調用!
好消息是,這些項目確實添加到TabControl w /它們各自的標題。
現在問題就出現了,當WPF試圖對它們應用樣式後,窗口變得可見!
我對這個的TabItems默認樣式:
<Style TargetType="{x:Type TabItem}"
BasedOn="{StaticResource TISTabItem}">
<Setter Property="Width">
<Setter.Value>
<MultiBinding Converter="{StaticResource convCategoryTabWidthConverter}">
<Binding RelativeSource="{RelativeSource AncestorType={x:Type TabControl}, Mode=FindAncestor}" />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type TabControl}, Mode=FindAncestor}"
Path="ActualWidth" />
</MultiBinding>
</Setter.Value>
</Setter>
</Style>
和轉換器:
public class CategoryTabWidthConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (values == null || values.Count() < 1)
throw new ArgumentException("Values array passed is invalid.", "values");
if(values[0] == DependencyProperty.UnsetValue)
{
return 0; // Added for breakpoint. Bailing out here!!!
}
TabControl tabCtrl = values[0] as TabControl;
Double w = (tabCtrl.ActualWidth/tabCtrl.Items.Count);
w = (w <= 1) ? 0.0 : (w - 1);
return w;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
備註:我使用這個轉換器和風格在其他兩個地方,那裏的TabItems靜態添加到XAML中!在這些情況下,它一切正常!
但是,當動態添加TabItems時,兩者都將TabControl RelativeSource和它的ActualWidth評估爲DependencyProperty.UnsetValue
。
我期望在這裏遇到一些邏輯錯誤。
什麼時候應用樣式?在TabItems被正確添加到內部樹之後還是之後? 有沒有人對我在這裏做錯了想法?
我會進一步調查,並提前謝謝你的幫助。