【问题标题】:WPF ComboBox - showing something different when no items are boundWPF ComboBox - 在没有绑定项目时显示不同的内容
【发布时间】:2009-05-20 03:17:24
【问题描述】:

我有一个 ComboBox,我想在 ItemsSource 属性为空时更改它的外观。当它处于该状态时,我想显示一个 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 属性为空时显示此内容?我尝试了几种不同的方法,每种方法都给了我错误消息“无法将值'ItemsSource'分配给属性'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 属性?我什至应该使用触发器吗?

谢谢!

【问题讨论】:

    标签: wpf combobox triggers


    【解决方案1】:

    尝试将{x:Null} 作为条件值而不是 0。

    我还通过将触发器移动到一个样式并稍微修改它来让它工作,见下文。

    <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}" .... >
    

    它只在一种样式中起作用的原因是,框架元素上的触发器集合中只允许直接使用 EventTriggers。对于属性触发器(如上),您需要使用一种样式(我每天都在学习)。

    FrameworkElement.Triggers

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

    【讨论】:

      猜你喜欢
      • 2010-11-11
      • 2021-03-11
      • 2016-03-12
      • 2022-01-03
      • 2014-11-11
      • 2013-07-14
      • 2023-03-02
      • 1970-01-01
      • 2018-09-06
      相关资源
      最近更新 更多