2010-11-03 73 views
1

我在列表框中拥有自己的样式,我使用样式数据模板和控制模板。 在数据模板中,我使用一些文本框创建列表框项目。在控件模板中,我想创建一个触发器,如果​​选择了列表框项目,它将更改某些文本框的前景色。未找到WPF-触发器目标

下面是一些从款式:

<Style x:Key="lbStyle" TargetType="{x:Type ListBox}"> 
     <Setter Property="ItemTemplate"> 
      <Setter.Value> 
       <DataTemplate> 
        <Grid Name="MainGrid"> 
         <TextBlock Name="tbName" Text="{Binding Value.nick}" 
             Grid.Column="0" Grid.Row="0" Margin="2,2,2,2" 
             FontSize="13" FontWeight="Medium"></TextBlock> 
        </Grid> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="ListBoxItem"> 
        <ControlTemplate.Triggers> 
         <Trigger Property="IsSelected" Value="true"> 
          <Setter TargetName="tbName" Property="Foreground" Value="Black"/> 
         </Trigger> 
        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 

    </Style> 

问题是,我得到的编译错误:无法找到触发目标tbName。

回答

0
<Style TargetType="ListBox"> 
    <Setter Property="ItemTemplate"> 
     <Setter.Value> 
      <DataTemplate> 
       <TextBlock Text="{Binding}" Margin="2" FontSize="13" FontWeight="Medium"> 
        <TextBlock.Style> 
         <Style BasedOn="{StaticResource {x:Type TextBlock}}" TargetType="TextBlock"> 
          <Style.Triggers> 
           <DataTrigger Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBoxItem}, Path=IsSelected}" Value="True"> 
            <Setter Property="Foreground" Value="Black"/> 
           </DataTrigger> 
          </Style.Triggers> 
         </Style> 
        </TextBlock.Style> 
       </TextBlock> 
      </DataTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
0

您的模板代码不正确。您将ListBoxItem模板应用于ListBox模板。此外,您没有在ControlTemplate内添加任何内容。

我已经rewrited它:

<Style x:Key="itemStyle" TargetType="{x:Type ListBoxItem}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="ListBoxItem"> 
        <ContentPresenter x:Name="itemContent"/> 

        <ControlTemplate.Triggers> 
         <Trigger Property="IsSelected" Value="true"> 
          <Setter TargetName="itemContent" Property="TextBlock.Foreground" Value="Red"/> 
         </Trigger> 
        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

列表框使用应用的风格:

<ListBox ItemContainerStyle="{StaticResource itemStyle}" />