[英]Change binding of element inside template
I have a DataGrid where different items in the row can be either editable or readonly. 我有一个DataGrid,其中行中的不同项目可以是可编辑的也可以是只读的。
If I had a single cell that needed to be make read only at will, I'd use something like 如果我有一个需要随意设置为只读的单元格,则可以使用类似
<DataGrid.Resources>
<!-- the non-editing cell -->
<DataTemplate x:Key="ReadonlyCellTemplate">
<TextBlock Text="{Binding UserName}" />
</DataTemplate>
<!-- the editing cell -->
<DataTemplate x:Key="EditableCellTemplate">
<TextBox Text="{Binding UserName}" />
</DataTemplate>
</DataGrid.Resources>
And than I would apply that template to a column of my choice. 然后,我将该模板应用于自己选择的列。
<DataGridTemplateColumn CellTemplate="{StaticResource ReadonlyCellTemplate}" Header="User name">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<!-- the additional layer of content presenter -->
<ContentPresenter x:Name="Presenter" Content="{Binding}" ContentTemplate="{StaticResource ReadonlyCellTemplate}" />
<DataTemplate.Triggers>
<!-- dynamically switch the content template by IsEditable binding -->
<DataTrigger Binding="{Binding CreationFieldsEditable}" Value="True">
<Setter TargetName="Presenter" Property="ContentTemplate" Value="{StaticResource EditableCellTemplate}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
I want to be able to change {Binding UserName}
inside the template, so I can apply the template to different columns. 我希望能够更改模板内的
{Binding UserName}
,因此可以将模板应用于不同的列。
How do I do that? 我怎么做?
instead of 代替
<DataTemplate x:Key="EditableCellTemplate">
<TextBox Text="{Binding UserName}" />
</DataTemplate>
you need to extend the template: 您需要扩展模板:
<DataTemplate x:Key="t1">
<TextBox Text="{Binding UserName1}" />
</DataTemplate>
<DataTemplate x:Key="t2">
<TextBox Text="{Binding UserName2}" />
</DataTemplate>
<DataTemplate x:Key="EditableCellTemplate">
<ContentPresenter x:Name="ctp" />
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding MyProperty}"
Value="1">
<Setter TargetName="ctp"
Property="ContentTemplate"
Value="{StaticResource t1}" />
</DataTrigger>
<DataTrigger Binding="{Binding MyProperty}"
Value="2">
<Setter TargetName="ctp"
Property="ContentTemplate"
Value="{StaticResource t2}" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
This should work if I understand your idea well. 如果我对您的想法很了解,这应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.