要在您的ShowChildItems
财产中UserControl
管理Visibility
您的孩子GridView
,您首先需要将其设为DependencyProperty
:
public static readonly DependencyProperty ShowChildItemsProperty =
DependencyProperty.Register("showChildItems", typeof (bool), typeof (MyUserControl), new PropertyMetadata(true));
public bool ShowChildItems
{
get { return (bool) GetValue(ShowChildItemsProperty); }
set { SetValue(ShowChildItemsProperty, value); }
}
在内部,UserControl
您将GridView
Visibility
使用ElementName
语法将 the 绑定到该属性 - 这样,绑定的内容无关紧要GridView
DataContext
:
<GridView Visibility="{Binding ShowChildItems, ElementName=ControlRoot, Converter={StaticResource VisibilityConverter}}" ItemsSource="{Binding ChildItems}">
为此,您需要将名称设置为UserControl
的根节点(我省略了其余属性):
<UserControl
x:Name="ControlRoot">
我还使用转换器将bool
属性绑定到Visibility
:
<UserControl.Resources>
<local:BoolToVisibilityConverter x:Key="VisibilityConverter" />
</UserControl.Resources>
这是它的代码:
public class BoolToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (!(value is bool)) return Visibility.Collapsed;
return (bool) value ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
我希望这是你所要求的。根据您的问题,我不太确定。