WPF ComboBox - 在没有绑定项目时显示不同的内容

时间:2009-05-20 03:17:25

标签: wpf combobox triggers

我有一个ComboBox,我想在ItemsSource属性为null时更改其外观。当它处于该状态时,我想在其中显示带有文本“Retrieving data”的TextPanel,并给它看一下类似于带水印的文本框。

我想这样做我需要一个ControlTemplate和一个触发器。我在这里有ControlTemplate:

<ControlTemplate x:Key="LoadingComboTemplate" TargetType="{x:Type ComboBox}">  
    <Grid>  
        <TextBlock x:Name="textBlock" Opacity="0.345" Text="Retrieving data..." Visibility="Hidden" />  
    </Grid>  
    <!--  
    <ControlTemplate.Triggers>  
        <Trigger Property="ComboBox.ItemsSource" Value="0">  
            <Setter Property="Visibility" Value="Visible" />  
        </Trigger>  
    </ControlTemplate.Triggers>  
    -->  
</ControlTemplate>  

但我的问题是如何在ItemsSource属性为null时设置触发器来显示它?我尝试了几种不同的方法,并且每种方式都给了我错误消息“Value'TartsSource'不能分配给属性'Property'。无效的PropertyDescriptor值。”。我的ComboBox xaml是这个(包括尝试的触发器):

<ComboBox Margin="112,35,80,0"   
      Name="MyComboBox"   
      Height="22.723"   
      VerticalAlignment="Top"   
      DisplayMemberPath="FriendlyName"   
      SelectedValuePath="Path"   
      TabIndex="160"   
      >  
    <Trigger>  
        <Condition Property="ItemsSource" Value="0" />  
        <Setter Property="Template" Value="{StaticResource LoadingComboTemplate}" />  
    </Trigger>    
</ComboBox>  

现在触发器应该在ComboBox上还是在ControlTemplate上?如何访问ComboBox的ItemsSource属性?我甚至应该使用触发器吗?

谢谢!

1 个答案:

答案 0 :(得分:4)

尝试将{x:Null}放入条件的值而不是0。

此外,我通过将Trigger移动到一个样式并稍微修改它来实现它,见下文。

<Style TargetType="ComboBox" x:Key="LoadingComboStyle">
    <Style.Triggers>
        <Trigger Property="ItemsSource" Value="{x:Null}">
            <Setter Property="Template" Value="{StaticResource LoadingComboTemplate}" />
        </Trigger>
    </Style.Triggers>
</Style>

<ComboBox Style="{StaticResource LoadingComboStyle}" .... >

它仅适用于样式的原因是,直接在Framework Element上的触发器集合中只允许EventTriggers。对于属性触发器(如上所述),您需要使用样式(我每天都学习一些东西)。

请参阅FrameworkElement.Triggers

  

请注意,在元素上建立的触发器集合仅支持EventTrigger,而不支持属性触发器(Trigger)。如果需要属性触发器,则必须将它们放在样式或模板中,然后直接通过Style属性将该样式或模板分配给元素,或者通过隐式样式引用间接分配。