Is it possible to create a template for a GridViewColumn, without fixed data binding?

*爱你&永不变心* 提交于 2019-12-02 00:42:49

The only method i can think of right now to inline this is using markup-extensions as you try to pass more than one value to one property.

Getting variable data into the template seems to be non-trivial though and the following approach using a static property is quite the hack, maybe you can think of something better:

<ListView ItemsSource="{Binding Data}">
    <ListView.Resources>
        <!-- x:Shared="False" because otherwise the Tag extension is only evaluated the first time the resource is accessed -->
        <DataTemplate x:Shared="false" x:Key="TemplateBuilder_BaseTemplate">
            <TextBox Text="{me:TemplateBuilderTag}" Width="100" LostFocus="TextBox_LostFocus" />
        </DataTemplate>
    </ListView.Resources>
    <ListView.View>
        <GridView>
            <GridViewColumn CellTemplate="{me:TemplateBuilder Name}"  />
            <GridViewColumn CellTemplate="{me:TemplateBuilder Occupation}" />
        </GridView>
    </ListView.View>
</ListView>
public class TemplateBuilderExtension : MarkupExtension
{
    public string Path { get; set; }

    public TemplateBuilderExtension() { }
    public TemplateBuilderExtension(string path)
    {
        Path = path;
    }

    // Here be dirty hack.
    internal static string TagPath { get; private set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        TagPath = Path;
        var resourceExt = new StaticResourceExtension("TemplateBuilder_BaseTemplate");
        // This line causes the evaluation of the Tag as the resource is loaded.
        var baseTemplate = resourceExt.ProvideValue(serviceProvider) as DataTemplate;
        return baseTemplate;
    }
}

public class TemplateBuilderTagExtension : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return new Binding(TemplateBuilderExtension.TagPath);
    }
}

I tried to use a custom service provider when getting the resource but unfortunately it did not arrive in ProvideValue of the tag, that would have been a better way to get the path accross.

You could of course create the template dynamically from scratch in the TemplateBuilderExtension, that way you will not run into such issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!