【问题标题】:Binding only works using ElementName, why?绑定只能使用 ElementName,为什么?
【发布时间】:2014-04-25 16:14:31
【问题描述】:

这是我的场景的一些代码 sn-ps。在 .xaml 方面,我有一个 ItemsControl:

<ItemsControl ItemsSource="{Binding StatList}" ItemTemplate="{StaticResource statBox}"></ItemsControl>

StatList 只是一个对象列表。

DataTemplate 包含此 TextBlock

                    <TextBlock x:Name="DataTextBlock" Background="Transparent" DockPanel.Dock="Top" HorizontalAlignment="Center"
                        Foreground="White" FontSize="11">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Loaded">
                            <iBehaviors:InvokeMethodTrigger Method="UpdateBinding"
                                    Target="{Binding DataContext, RelativeSource={RelativeSource TemplatedParent}}"
                                    Parameter="{Binding ., RelativeSource={RelativeSource AncestorType=TextBlock}}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </TextBlock>

这在我第一次在我的 ViewModel 上设置我的 StatList 时起作用,TextBlock 本身作为参数传递给 InvokeMethodTrigger。但是,如果我更改视图模型上的 StatList,则下次发生 Loaded 事件时,触发 InvokeMethodTrigger 时,Parameter 为 null。

奇怪的是,当我将参数绑定更改为:

Parameter="{Binding ElementName=DataTextBlock}"

当我更改我的 StatList 时,它第二次起作用,TextBlock 作为参数传递。我一辈子都想不通为什么!有什么解释吗?

【问题讨论】:

    标签: wpf binding


    【解决方案1】:

    你可以在后面的代码中这样做:

        SlatList slat = new SlatList();
        ItemControl.ItemSource = slat;
        ItemControl.DataContext = slat;
    

    确保为 itemcontrol 指定名称并将“ItemControl”替换为该名称。

    在 XAML 中:

      <ItemsControl ItemsSource="{Binding StatList}" DataContext="{Binding SlatList} ItemTemplate="{StaticResource statBox}"> </ItemsControl>
    

    【讨论】:

      猜你喜欢
      • 2011-06-06
      • 2012-02-25
      • 2012-10-12
      • 1970-01-01
      • 2013-02-23
      • 2014-02-25
      • 2012-07-14
      • 2015-09-02
      • 1970-01-01
      相关资源
      最近更新 更多