如何从 DataTemplate 检索元素并绑定到它?

发布于 2024-11-02 03:07:03 字数 1090 浏览 1 评论 0原文

我试图在代码中获取 DataTemplate 中元素的句柄。我正在代码中创建一系列 DataGridTemplateColumns,然后将其分配给网格。 我希望能够从 xaml 中检索 DataTemplate,找到我的元素并绑定到该特定元素。

这是我想要实现的一个简短的示例代码:

<DataTemplate x:Key="dataTemplate">
    <Grid TextBlock.Foreground="LightGreen" Background="Yellow">
        <TextBlock x:Name="txt" />
    </Grid>
</DataTemplate>
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "Last Name";
Binding b = new Binding("LastName");
DataTemplate dtemplate = (DataTemplate)FindResource("dataTemplate");
TextBlock textBlock = dtemplate.FindName("txt", this);
textBlock.SetBinding(TextBlock.TextProperty, b);
col.CellTemplate = dtemplate;

grid.Columns.Add(col);

也许可以进一步解释这一点: 我正在尝试动态创建一组 DataGridTemplateColumns 并将其应用到数据网格。由于在向我提供源之前我不知道要绑定的属性,因此我无法创建嵌套在其自身内的 DataTemplate,该 DataTemplate 已内置此绑定。例如:

<TextBlock Text={Binding=LastName} ... >

所以我被迫在运行时创建一组 DataGridTemplateColumn ,在我的资源中查找 DataTemplate,然后尝试将该列绑定到我的数据源上的属性(如 LastName)。

I am trying to get a handle on an element within my DataTemplate in code. I am creating a series of DataGridTemplateColumns in code which I then assign to a grid.
I want to be able to retrieve the DataTemplate from the xaml, find my element and bind to that particular element.

Here is a short sample code what I am trying to achieve:

<DataTemplate x:Key="dataTemplate">
    <Grid TextBlock.Foreground="LightGreen" Background="Yellow">
        <TextBlock x:Name="txt" />
    </Grid>
</DataTemplate>
DataGridTemplateColumn col = new DataGridTemplateColumn();
col.Header = "Last Name";
Binding b = new Binding("LastName");
DataTemplate dtemplate = (DataTemplate)FindResource("dataTemplate");
TextBlock textBlock = dtemplate.FindName("txt", this);
textBlock.SetBinding(TextBlock.TextProperty, b);
col.CellTemplate = dtemplate;

grid.Columns.Add(col);

Maybe to explain this further:
I am trying to create a set of DataGridTemplateColumns on the fly and apply that to a Datagrid. Since I don't know the property to bind to until the time a source gets presented to me I cannot create a DataTemplate that nested within itself has this binding already build in. Like:

<TextBlock Text={Binding=LastName} ... >

So I am forced to create a set of DataGridTemplateColumn in runtime, look for DataTemplate in my resources and THEN try to bind that column to a property (like LastName) on my datasource.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

半夏半凉 2024-11-09 03:07:03

我会通过 CellStyle 来解决这个问题:

<DataGrid.Resources>
    <Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="TextBlock.Foreground" Value="LawnGreen"/>
        <Setter Property="Background" Value="Yellow"/>
    </Style>
</DataGrid.Resources>
DataGridTextColumn col = new DataGridTextColumn();
col.Binding = new Binding("Name");
col.CellStyle = dataGrid.Resources["CellStyle"] as Style;
dataGrid.Columns.Add(col);

还有一些方法可以通过 DataTemplates 来做到这一点,但在这种情况下似乎没有必要(除非您的问题更复杂)。

I would approach this via CellStyle instead:

<DataGrid.Resources>
    <Style x:Key="CellStyle" TargetType="{x:Type DataGridCell}">
        <Setter Property="TextBlock.Foreground" Value="LawnGreen"/>
        <Setter Property="Background" Value="Yellow"/>
    </Style>
</DataGrid.Resources>
DataGridTextColumn col = new DataGridTextColumn();
col.Binding = new Binding("Name");
col.CellStyle = dataGrid.Resources["CellStyle"] as Style;
dataGrid.Columns.Add(col);

There are also ways to do this via DataTemplates but it does not seem necessary in this case (unless your problem is more complex).

燃情 2024-11-09 03:07:03

我对这个问题的解决方案是这样的:

 GridView viewLayout = new GridView();

        for (int i = 0; i < Apprefs.tables[0].Headers.Count(); i++)
        {
            GridViewColumn gvc = new GridViewColumn();
            string colName = Apprefs.tables[0].Headers[i];
            gvc.Header = colName;
            gvc.Width = 80;
            gvc.CellTemplate = SetTemplete(i); ;
            viewLayout.Columns.Add(gvc);
       }

        listview1.View = viewLayout;

        //set binding
        listview1.ItemsSource = Apprefs.tables[0].Rows;

然后:

    /// <summary>
    /// Create DataTemplate
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    private DataTemplate SetTemplete(int i)
    {
        DataTemplate template = new DataTemplate();

        //set stack panel 
        FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel));
        sp.Name = "spBind";
        sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

        //set textblock
        FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
        sp.Name = "tbBind";
        Binding b = new Binding();
        string ito = "[" + i.ToString() + "]";  // bind by index
        b.Path = new PropertyPath(ito);
        tb.SetBinding(TextBlock.TextProperty, b);
        sp.AppendChild(tb);

        //set the visual tree of the data template 
        template.VisualTree = sp;

        return template;
    }

My solution to the problem is something like this:

 GridView viewLayout = new GridView();

        for (int i = 0; i < Apprefs.tables[0].Headers.Count(); i++)
        {
            GridViewColumn gvc = new GridViewColumn();
            string colName = Apprefs.tables[0].Headers[i];
            gvc.Header = colName;
            gvc.Width = 80;
            gvc.CellTemplate = SetTemplete(i); ;
            viewLayout.Columns.Add(gvc);
       }

        listview1.View = viewLayout;

        //set binding
        listview1.ItemsSource = Apprefs.tables[0].Rows;

and then:

    /// <summary>
    /// Create DataTemplate
    /// </summary>
    /// <param name="i"></param>
    /// <returns></returns>
    private DataTemplate SetTemplete(int i)
    {
        DataTemplate template = new DataTemplate();

        //set stack panel 
        FrameworkElementFactory sp = new FrameworkElementFactory(typeof(StackPanel));
        sp.Name = "spBind";
        sp.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);

        //set textblock
        FrameworkElementFactory tb = new FrameworkElementFactory(typeof(TextBlock));
        sp.Name = "tbBind";
        Binding b = new Binding();
        string ito = "[" + i.ToString() + "]";  // bind by index
        b.Path = new PropertyPath(ito);
        tb.SetBinding(TextBlock.TextProperty, b);
        sp.AppendChild(tb);

        //set the visual tree of the data template 
        template.VisualTree = sp;

        return template;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文