【问题标题】:WPF: Bind to element in DataTemplate in ResourceDictionaryWPF:绑定到 ResourceDictionary 中的 DataTemplate 中的元素
【发布时间】:2013-06-13 15:26:52
【问题描述】:

我想绑定到从位于ResourceDictionary 中的DataTemplate 动态插入到我的窗口中的元素属性(在我的特定情况下是ListBox 的SelectedItems.Count)。当计数达到一定数量的ListBoxItems 被选中时,我想启用/禁用一个按钮。我认为这会起作用:

<Style TargetType="Button">
  <Style.Triggers>
    <DataTrigger Binding="{Binding Source={StaticResource myResourceKey}, Path=myListBox.SelectedItems.Count}" Value="25">
      <Setter Property="IsEnabled" Value="False"/>
    </DataTrigger>
  </Style.Triggers>
</Style>

但我收到以下错误:

System.Windows.Data Error: 40 : BindingExpression path error: 'myListBox' property not found on 'object' ''DataTemplate' (HashCode=50217655)'. BindingExpression:Path=aoiListBox.SelectedItems.Count; DataItem='DataTemplate' (HashCode=50217655); target element is 'Button' (Name='myBtn'); target property is 'NoTarget' (type 'Object')

我怎样才能实现这种绑定?提前致谢。

【问题讨论】:

    标签: wpf binding datatemplate resourcedictionary


    【解决方案1】:

    您可以编写一个解决方法,但我强烈建议不要以这种方式实现它。考虑一下,ResourceDictionary 中的样式是一个空资源,它应该与应用程序中的任何特定实例(在您的情况下为 myListBox)解耦。问题是,您不能在另一个 Button 上使用这种 malformed 样式。所以你不需要,最好你不应该,将它声明为资源。

    我绝对建议直接在Button 中声明这个Style。例如

    <ListBox x:Name="myListBox" />
    <Button>
        <Button.Style>
            <Style TargetType="Button">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=myListBox, 
                                 Path=SelectedItems.Count}" Value="25">
                        <Setter Property="IsEnabled" Value="False"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style> 
        </Button.Style>
    </Button>
    

    另外,我会通过ElementName 属性使用Binding

    【讨论】:

      猜你喜欢
      • 2010-11-20
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      相关资源
      最近更新 更多