[英]Change DataGrid cell content/template on row select
我想要的行為是:我有一個帶有單個列的數據網格。 它綁定到包含有關某個人的各種信息的項目列表。 未選中時,該行僅顯示此人的姓名。 當選擇該行(即單擊)時,我將顯示有關此人的更多信息。
我的第一次嘗試是使用DataGridTemplateColumn,其中CellTemplate是ContentControl。 ContentControl的樣式由所選行的狀態確定。
我的風格:
<DataTemplate x:Key="NotSelectedTemplate">
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Path=DataContext.PatientName.FormattedName, Mode=OneWay, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Height="60" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContentControl}, Path=DataContext.PatientName.FormattedName, Mode=OneWay, BindsDirectlyToSource=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
<Style x:Key="SelectableContentStyle" TargetType="{x:Type ContentControl}">
<Style.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="False">
<Setter Property="ContentTemplate" Value="{StaticResource NotSelectedTemplate}" />
</DataTrigger>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}}, Path=IsSelected}" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</DataTrigger>
</Style.Triggers>
</Style>
我的數據網格列:
<DataGrid.Columns>
<DataGridTemplateColumn Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ContentControl Style="{StaticResource SelectableContentStyle}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
這種方法有效 ,但是每個DataTemplate中的綁定都很難看。 我在WPF方面相對缺乏經驗,所以我確信必須有一種更好的方法來實現這一點。
基本上,1)是否有更好的方法來實現此行為? 2)有沒有更好的方法綁定到DataTemplate,所以我每次訪問屬性時都不會追逐RelativeSources?
您可以為ContentTemplateProperty
實現一個模板選擇器,該選擇器將兩個模板作為屬性,並具有一個布爾屬性在它們之間進行切換。
壞消息是基類( DataTemplateSelector
)不是依賴對象,因此不支持您的flag屬性的綁定。 在那種情況下,我通過添加一個Config
屬性來解決該問題,該屬性包含一個自定義類的實例,然后您可以將該類作為DependencyObject
的子類並在其中定義依賴項屬性。 當然,這將再次使您的代碼膨脹,並且綁定會受到限制,因為從非正式的角度來說,綁定范圍會中斷。
另一個選擇可能是通過DynamicResource
引用SelectableContentStyle
的兩個模板,這樣,您只需要編寫一次DataTrigger
開關,而只需在單個DataTemplates
中的資源中定義兩個模板即可。
有關示例,請參見此答案 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.