如何从DataTemplate中检索元素并将其绑定到代码中? [英] How to retrieve an element from a DataTemplate and bind to it in code?
本文介绍了如何从DataTemplate中检索元素并将其绑定到代码中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
嗨
我正在尝试动态创建一组DataGridTemplateColumns并将其应用于DataGrid.使用 DataGridTextColumn 很容易,并且允许我在创建列时绑定到Dependency属性(请参见下面的代码):
I am trying to create a set of DataGridTemplateColumns on the fly and apply that to a DataGrid. Using the DataGridTextColumn is easy and allows me to bind to a Dependency Property as I create the columns (see code below):
private void CreateTextColumn(string Header, int width, string BindField)
{
DataGridTextColumn col = new DataGridTextColumn();
col.Header = Header;
col.Width = new DataGridLength(width, DataGridLengthUnitType.Star);
col.Binding = new Binding(BindField);
dgrid.Columns.Add(col);
}
推荐答案
以下代码可能会对您有所帮助.
Probably the below code may help you.
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "New Columns";
Binding b1 = new Binding("Description");
b1.Mode = BindingMode.TwoWay;
FrameworkElementFactory factory1 = new FrameworkElementFactory(typeof(TextBlock));
factory1.SetValue(TextBlock.TextProperty, b1);
DataTemplate dtemplate = new DataTemplate();
dtemplate.VisualTree = factory1;
col.CellTemplate = dtemplate;
//DataTemplate dtemplate = (DataTemplate)FindResource("dataTemplate");
//col.CellTemplate = dtemplate;
dataGrid1.Columns.Add(col);
Another approach would be having your Binding in the DataTemplate like below. Then your code will work
<Window.Resources>
<DataTemplate x:Key="dataTemplate">
<TextBlock Text="{Binding Description}" />
</DataTemplate>
</Window.Resources>
这篇关于如何从DataTemplate中检索元素并将其绑定到代码中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文