更改DataTemplate文本块可见性由父容器类型确定

时间:2017-02-23 02:19:14

标签: wpf xaml

我有<DataTemplate>定义如下,其中包含<TextBlock>

<DataTemplate><ListBox>的多个实例中使用,并在<ContentControl>

的其他地方重复使用

为简洁而简化的注释代码

<DataTemplate x:Key="SetsItemTemplate" DataType="viewModel:SetVm">
   <TextBlock 
       Visibility="{Binding <somethign here i guess>, 
          ConverterParameter=collapse, 
          Converter={StaticResource BoolToVisConverter}}">
   </TextBlock>
</DataTemplate>

<ListBox ItemTemplate="{StaticResource SetsItemTemplate}" />

<ContentControl ContentTemplate="{StaticResource SetsItemTemplate}" />

<TextBlock>有一个boolToVisibility Converter可以在某个条件下折叠<TextBlock>,但我确实需要这个条件来检查父容器是否为<ContentControl>

即如果<DataTemplate>父级是<ContentControl>,则<TextBlock>

崩溃

也许我可以使用名字来让这更容易(我不确定)

1 个答案:

答案 0 :(得分:1)

要访问父级,您需要获取sender或源对象。你无法使用IValueConverter获得此功能。但是,他们已经有了解决方案:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/9f3e4f6d-20d2-4c13-90a2-7c157ed4f8c3/ivalueconverter-pass-calling-object-as-converterparameter?forum=wpf

现在,您可以访问该元素并通过以下方式获取父级:

element = VisualTreeHelper.GetParent(element) as UIElement; 

希望它有所帮助!

相关问题