如何在DataTemplate中找到一个控件并在WPF中赋值?

我有一个DataTemplate绑定到Grid Group Header Section。 DataTemplate中有四个TextBlock,其中一个TextBlock包含Grid Header Column Value。 现在,我想将此TextBlock值拆分为三个,并将此值分配给Code Behind中的其他三个TextBlock。 可能吗?

 <!--  -->                                           protected void GetAllInfills() { List infillList = new List(); infillList=BLL.GetAllInfills(); if (infillList != null) { grdInfill.ItemsSource = infillList; grdInfill.GroupBy(grdInfill.Columns["GlassType"], ColumnSortOrder.Ascending); grdInfill.GroupBy(grdInfill.Columns["GlassDescription"], ColumnSortOrder.Ascending); grdInfill.AutoExpandAllGroups = true; } } 

从上面marukup我想访问TextBlock控件,即’ txtdescription ‘,其中包含Grid txtdescription ‘的组头部分值,现在我想将此值int拆分为三个值,即txtdescription.Split(’*’)并赋值到其他三个文本块,即来自代码隐藏的DataTemplate中的txtdesc1,txtdesc2,txtdesc3。

由于您请求了示例,我使用ListBox提供示例。
XAML

                       

代码隐藏

 public partial class DataTemplateWindow : Window { public DataTemplateWindow() { DisplayText = "Some*Text*With*Separators"; string [] splittedTextArray = DisplayText.Split('*'); TextBlock0 = splittedTextArray[0]; TextBlock1 = splittedTextArray[1]; TextBlock2 = splittedTextArray[2]; ListBoxItems = new List(); ListBoxItems.Add("Item 1"); InitializeComponent(); this.DataContext = this; } public string DisplayText { get; set; } public string TextBlock0 { get; set; } public string TextBlock1 { get; set; } public string TextBlock2 { get; set; } public List ListBoxItems { get; set; } } 

编辑以回应其他信息

在WPF中,您可以使用元素绑定,它允许您访问给定元素的任何属性。 由于您要访问txtdescription textblock的text属性,因此您必须使用Element Binding。 但是你不想把它分成三个TextBlocks。 所以你需要一个转换器。

使用下面的代码进行元素绑定

      

这是转换器代码

 public class SplitterConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { string combinedString = value as string; if (!string.IsNullOrEmpty(combinedString)) { string [] splitArray = combinedString.Split('*'); int postion = int.Parse(parameter as string); switch (postion) { case 0: return splitArray[0]; case 1: return splitArray[1]; case 2: return splitArray[2]; default: return null; } } return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 

最后在xaml中包含Converter Namespace

     ....