DataTemplate内部绑定不起作用

问题描述 投票:-1回答:1

我很幸运用DataTrigger更改View,但是当Trigger内部的绑定不起作用时。我做错了什么?我的资源风格

<Style x:Key="AgentPositionContentTemplateSelector" TargetType="{x:Type ContentControl}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <DataTemplate >
                <!--Agent name dont changed, Binding to "Agent" property dont work -->
                <TextBlock  Background="BlueViolet" Text="{Binding Agent}"></TextBlock> 
            </DataTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <!--But this binding work perfect! DataTemplate changed!-->
        <DataTrigger Binding="{Binding Agent.PositionId, Converter={StaticResource IntToPositionDictionaryConverter} }"><!--Int to Enum-->
            <DataTrigger.Value>
                <enum:PositionDictionary>Merchandiser</enum:PositionDictionary>
            </DataTrigger.Value>

            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <!--And this binding don't work also!-->
                        <TextBlock Background="Aqua" Text="{Binding Agent}"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </DataTrigger>
    </Style.Triggers>
</Style>

我的看法:

<ListBox Name="AgentsListBox" IsSynchronizedWithCurrentItem="True" SelectionMode="Single"
                 DisplayMemberPath="Agent" Grid.Column="0" ItemsSource="{Binding CCRTeamRows}"><!--SelectedItem="{Binding SelectedAgent}"-->

        </ListBox>
<!--This also work correct-->
<TextBlock  Text="{Binding Agent, Mode=OneWay, UpdateSourceTrigger=PropertyChanged }"></TextBlock>
<TextBlock  Text="{Binding Position, Mode=OneWay, UpdateSourceTrigger=PropertyChanged }"></TextBlock>
<TextBlock Text="{Binding Claster,  UpdateSourceTrigger=PropertyChanged }"></TextBlock>

<ContentControl Style="{DynamicResource AgentPositionContentTemplateSelector}" /> 

请带我去正确的路。

c# wpf xaml data-binding datatrigger
1个回答
0
投票

在DataTemplates中,您需要使用RelativeSource绑定到ListBoxItem,然后使用Path = DataContext.Agent:

Text="{Binding Path=DataContext.Agent, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}"
© www.soinside.com 2019 - 2024. All rights reserved.