【发布时间】:2011-11-02 09:37:19
【问题描述】:
这可能吗?
我有一个 ListView,我想为列创建一个模板,这样我标记为“cellTextBox”的每一列都会显示一个文本框(并且还在 LostFocus 事件上调用 TextBox_LostFocus())。我真的很想使用一个模板,而不是为每一列定义一个 DockPanel 和 TextBox。但是,每一列都将绑定到数据源中的不同列。
换句话说,我想要一个 GridViewColumns 的“千篇一律”,它允许我为每个列指定不同的绑定路径。
我尝试了类似的方法(除其他外),但它不起作用。
有什么想法吗?
<Page.Resources>
<DataTemplate x:Key="cellTextBox">
<DockPanel>
<TextBox
LostFocus="TextBox_LostFocus"
Width="100"
Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=DisplayMemberBinding}"
/>
</DockPanel>
</DataTemplate>
</Page.Resources>
<StackPanel>
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled"
HorizontalAlignment="Stretch"
ItemsSource="{Binding Tables[0]}"
Width="Auto"
x:Name="Service_Tasks">
<ListView.View>
<GridView>
<GridViewColumn Width="120" CellTemplate="{StaticResource cellTextBox}" DisplayMemberBinding={Binding Path=Field1} Header="Field1" />
<GridViewColumn Width="120" CellTemplate="{StaticResource cellTextBox}" DisplayMemberBinding={Binding Path=Field2} Header="Field2" />
<GridViewColumn Width="120" CellTemplate="{StaticResource cellTextBox}" DisplayMemberBinding={Binding Path=Field3} Header="Field3" />
<GridViewColumn Width="120" CellTemplate="{StaticResource cellTextBox}" DisplayMemberBinding={Binding Path=FieldN} Header="FieldN" />
<!-- ... other columns ... -->
</GridView>
</ListView.View>
</ListView>
</StackPanel>
编辑 - 我想我会分享 @H.B. 解决方案的 Visual Basic 翻译,它对我有用。也许这会对其他人有所帮助。
Imports System.Windows.Markup
Public Class TemplateBuilderExtension : Inherits StaticExtension
Dim _path As String
Shared _tagpath As String
'Private TagPath As String
Shared Property TagPath As String
Get
TagPath = _tagpath
End Get
Private Set(ByVal value As String)
_tagpath = value
End Set
End Property
Property Path As String
Get
Path = _path
End Get
Set(ByVal value As String)
_path = value
End Set
End Property
Public Overrides Function ProvideValue(ByVal serviceProvider As System.IServiceProvider) As Object
TagPath = Path
Dim resourceExt = New StaticResourceExtension("TemplateBuilder_BaseTemplate")
'Dim baseTemplate As DataTemplate = DirectCast(resourceExt.ProvideValue(serviceProvider), DataTemplate)
ProvideValue = DirectCast(resourceExt.ProvideValue(serviceProvider), DataTemplate)
End Function
Public Sub New()
MyBase.new()
End Sub
Public Sub New(ByVal Path As String)
Me.Path = Path
End Sub
End Class
Public Class TemplateBuilderTagExtension : Inherits MarkupExtension
Public Sub New()
MyBase.New()
End Sub
Public Overrides Function ProvideValue(ByVal serviceProvider As System.IServiceProvider) As Object
ProvideValue = New Binding(TemplateBuilderExtension.TagPath)
End Function
End Class
显然,XAML 是相同的,无论如何。
不要忘记将以下命名空间引用添加到您的根级标记:
xmlns:me="clr-namespace:WpfApplication1",将WpfApplication 替换为应用程序的根命名空间(可以在应用程序的属性中找到)。
再次感谢@H.B.!
【问题讨论】:
标签: wpf xaml data-binding datatemplate