【问题标题】:Binding DataTemplate content绑定 DataTemplate 内容
【发布时间】:2012-09-21 13:12:11
【问题描述】:

我有以下DataTemplate

<DataTemplate x:Key="ButtonTemplate">
    <Button Click="Cell_Click">
        <Button.Template>
            <ControlTemplate TargetType="{x:Type Button}">
                <TextBlock x:Name="TBlock" />
            </ControlTemplate>
        </Button.Template>
    </Button>
</DataTemplate>

我将这个DataTemplate 用作GridViewColumn.CellTemplate,但是当我添加新列时,我必须动态绑定TextBlockText 属性:

GridViewColumn column = new GridViewColumn();
column.CellTemplate = Resources["ButtonTemplate"] as DataTemplate;
// How to get the TBlock (TextBlock) of CellTemplate and bind its property here?
MyGridView.Columns.Add(column);

我该怎么办?谢谢。

【问题讨论】:

    标签: c# wpf gridview binding datatemplate


    【解决方案1】:

    忘记修改模板,您最好在代码中从头开始创建它(或者您可以使用XamlReader.Parse 和动态插入绑定代码的 XAML 字符串)。

    【讨论】:

    • 我要解析的字符串是什么?
    • @Nick: 在 XAML 中包含您的数据模板的字符串,在 SO 上搜索方法名称,您会找到示例。
    【解决方案2】:

    您可以为 TextBlock 的 Loaded-Event 附加一个 EventHandler 并在那里创建绑定(基于 TextBlock 的 DataContext,如果信息足够的话)。

    【讨论】:

    • 问题是你的模板在创建列的时候没有实例化,所以不能使用FindName。您必须等到它加载完毕。那么你应该可以这样做:marcozhou.wordpress.com/2008/01/03/…
    • 我必须将 Text 属性绑定到名为 ("Box" + MyGridView.Coulmns.Count) 的属性。你能给我举个例子吗?在 XAML 中,如果我写 Text={Binding Box1} 它可以工作,但我必须动态选择正确的名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2011-07-21
    • 2011-12-09
    • 2016-11-30
    • 1970-01-01
    • 2018-06-14
    • 2022-10-24
    相关资源
    最近更新 更多