如果您可以修改您的vm:TabViewModel
I 应该将您的 IsVisible 更改为 Visibility 属性并使用以下 ContentTemplate:
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type vm:TabViewModel}">
<c:MyTabItem Visibility={Binding Visibility}/>
</DataTemplate>
</TabControl.ContentTemplate>
否则,您可以使用转换器将布尔 IsVisible 更改为 Visibility 枚举:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows;
namespace Something.Converters
{
[ValueConversion(typeof(bool), typeof(Visibility))]
public class BoolToVisibilityConverter : IValueConverter
{
#region IValueConverter Members
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is bool && targetType == typeof(Visibility))
{
bool val = (bool)value;
if (val)
return Visibility.Visible;
else
if (parameter != null && parameter is Visibility )
return parameter;
else
return Visibility.Collapsed;
}
throw new ArgumentException("Invalid argument/return type. Expected argument: bool and return type: Visibility");
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value is Visibility && targetType == typeof(bool))
{
Visibility val = (Visibility)value;
if (val == Visibility.Visible)
return true;
else
return false;
}
throw new ArgumentException("Invalid argument/return type. Expected argument: Visibility and return type: bool");
}
#endregion
}
}
在您的 xaml 中包含命名空间(您的根元素,在此示例中为 Window):
<Window xmlns:converters="clr-namespace:Something.Converters"
.../>
在您的资源中:
<Window.Resources>
<converters:BoolToVisibilityConverter x:Key="boolToVisibilityConverter"/>
</Window.Resources>
最后是绑定:
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type vm:TabViewModel}">
<c:MyTabItem Visibility={Binding IsVisible, Converter={StaticResource boolToVisibilityConverter}, ConverterParameter=Visibility.Collapsed}/>
</DataTemplate>
</TabControl.ContentTemplate>
我想就是这样:)
编辑:Ow 并将 ConverterParameter 更改为 Visibility.Collapsed 为 Visibility.Hidden 以隐藏 ;)