ContentControl对DataTemplate和DataContext属性的可见性

时间:2014-07-11 10:29:24

标签: wpf xaml visibility datatemplate contentcontrol

是否有可能更改ContentControl对内容DataTemplate的可见性?我有以下情况:

  • 自定义控件(具有四种状态的按钮 - 每种状态的背景图像)。
  • 在其他控件中将此控件用作属性的视图模型。
  • 具有相应DataTemplate的样式

    <!-- Default Style for Image Button -->
    <Style TargetType="{x:Type cont:StateImageButton}" BasedOn="{x:Null}">
          <Setter Property="Template" Value="{StaticResource ImageButtonTemplate}" />
    </Style>
    
    <!-- Default Representation of ImageButtonViewModel -->
    <DataTemplate DataType="{x:Type vm:StateImageButtonViewModel}">
          <cont:StateImageButton DefaultImage="{Binding DefaultImageName}"
                                           FocusedImage="{Binding FocusedImageName}"
                                           DisabledImage="{Binding DisabledImageName}"
                                           Command="{Binding Command}"
                                           ToolTip="{Binding ToolTip}"
                                           IsCancel="{Binding IsCancel}"
                                           IsDefault="{Binding IsDefault}"
                                           Visibility="{Binding IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"/>
    </DataTemplate>
    
  • 使用内容控件在应用程序中显示控件

    <StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right">
        <ContentControl Content="{Binding CancelButton}" Width="40" Height="40" Margin="5" />
        <ContentControl Content="{Binding ProtocolButton}" Width="40" Height="40" Margin="5" />
    </StackPanel>
    

如果第二个控件的viewmodel属性IsVisible设置为false,则控件不可见,但不会折叠。所以我在右边框和第一个控件之间有一个间隙。

如果我想要折叠第二个ContentControl,我必须在绑定数据的ContentControl属性上明确绑定IsVisible

<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right">
    <ContentControl Content="{Binding CancelButton}" Width="40" Height="40" Margin="5" />
    <ContentControl Content="{Binding ProtocolButton}" Width="40" Height="40" Margin="5"
                    Visibility="{Binding ProtocolButton.IsVisible, Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>

是否有可能避免这种情况?

编辑1:直接使用控件和DataContext

进行测试
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right">
    <con:StateImageButton DataContext="{Binding CancelButton}" Width="40" Height="40" Margin="5" />
    <con:StateImageButton DataContext="{Binding ProtocolButton}" Width="40" Height="40" Margin="5" />
    <!--
    <ContentControl Content="{Binding CancelButton}" Width="40" Height="40" Margin="5" />
    <ContentControl Content="{Binding ProtocolButton}" Width="40" Height="40" Margin="5" />-->
</StackPanel>

0 个答案:

没有答案