【问题标题】:WPF - How to bind item in DataTemplate?WPF - 如何在 DataTemplate 中绑定项目?
【发布时间】:2010-12-23 01:05:20
【问题描述】:

我遇到了一些问题。我创建了一个 DataTemplate 并将其放入 App.xaml 中,我想用它在我拥有的十几个 ListViews 中设置我的 CheckBoxes 样式。每个特定的 ListView 至少有一列带有 bool 值。

这是我制作的数据模板:

<DataTemplate x:Key="checkBoxDataTemplate">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>

        <CheckBox Grid.Column="0" Grid.Row="0" Style="{StaticResource DataGridCheckBox}" IsChecked="{WhatDoIPutHere?}" />
    </Grid>
</DataTemplate>

我正在尝试用它来代替它:

<GridViewColumn Header="Discovery Date">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Grid.Column="0" Grid.Row="0" Style="{StaticResource DataGridCheckBox}" IsChecked="{Binding CaseProperty.DiscoveryDate, Mode=OneWay, Converter={StaticResource booleanConverter},ConverterParameter='datetime'}" />
         </DataTemplate>
     </GridViewColumn.CellTemplate>
</GridViewColumn>

如您所见,我已将 IsChecked 绑定到附加到我的 ListView 的对象的特定属性。如果我将其替换为我的模板,如何绑定到 DataTemplate 中 CheckBox 的 IsChecked 属性?

提前致谢,
桑尼

【问题讨论】:

  • 我不明白为什么你的绑定应该改变,因为模板的实例绑定到同一个东西。
  • 您是否打算在实际实现中向 checkBoxDataTemplate 添加更多内容?现在它在功能上与内联模板相同,因此添加包含不同绑定所需的复杂性并没有真正的优势。
  • 您想要实现的是在不同的地方使用相同的数据模板并将其属性绑定到不同的东西?
  • 如果您尝试将此 DataTemplate 重新用于多个控件,我实际上并不认为 DataTemplates 是通用的。只要您只需要绑定一个属性,弗拉德的答案就可以工作,但除此之外,我建议您为不同的用途创建不同的 DataTemplates。此外,OJ 的评论也很到位
  • @All - 抱歉,我想我不是很清楚。基本上,我使用数据网格来显示大约两打不同的对象。大多数这些对象都有布尔属性,我想用复选框来表示。每个对象和属性都需要一个数据模板吗?我希望只制作一个模板并以某种方式重用它。

标签: wpf data-binding datatemplate


【解决方案1】:

你可以试试这个方法:

<CheckBox Grid.Column="0" Grid.Row="0" Style="{StaticResource DataGridCheckBox}"
          IsChecked="{Binding}" />

然后设置相应的DataContext。

【讨论】:

    【解决方案2】:

    我已经放弃了这种方法。我不认为 DataTemplates 被设计成以这种方式工作......哦,好吧......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多