开发者

WPF Grid with XmlDataProvider and ContentControl?

开发者 https://www.devze.com 2022-12-16 06:03 出处:网络
What is wrong with DataTemplate x:Key=\"CellTemplate\" not reaching the DataContext of the Grid\'s ContentControl?

What is wrong with DataTemplate x:Key="CellTemplate" not reaching the DataContext of the Grid's ContentControl?

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="WpfApplication1.Page1">
    <Page.Resources>
        <XmlDataProvider x:Key="xml">
            <x:XData>
                <root xmlns="">
                    <foo a="one" />
                    <foo a="two" />
                    <foo a="three" />
                    <foo a="four" />
                </root>
     开发者_高级运维       </x:XData>
        </XmlDataProvider>
    </Page.Resources>
    <Grid DataContext="{Binding Mode=Default, Source={StaticResource xml}}">
        <Grid.Resources>
            <DataTemplate x:Key="CellTemplate">
                <TextBlock Foreground="AntiqueWhite"
                           Text="{Binding Mode=Default, XPath=.}" />
                <DataTemplate.Triggers>
                    <DataTrigger Binding="{Binding XPath=.}" Value="three">
                        <Setter Property="TextBlock.FontWeight" Value="Bold" />
                    </DataTrigger>
                </DataTemplate.Triggers>
            </DataTemplate>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ContentControl Grid.Row="0" 
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[1]/@a}" />    
        <ContentControl Grid.Row="1"
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[2]/@a}" />    
        <ContentControl Grid.Row="2" 
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[3]/@a}" />
        <ContentControl Grid.Row="3" 
            ContentTemplate="{StaticResource CellTemplate}"
            DataContext="{Binding Mode=Default, XPath=/root/foo[4]/@a}" />
    </Grid>
</Page>


Figured it out, it's confusing, but the data context inside the data template is set to the content of the content control, not to its data context. Instead of setting the data context of each content control, set its content.

Example:

<ContentControl Grid.Row="1"
    ContentTemplate="{StaticResource CellTemplate}"
    Content="{Binding Mode=Default, XPath=/root/foo[1]/@a}" />

Or, alternatively:

<ContentControl Grid.Row="0" 
    ContentTemplate="{StaticResource CellTemplate}"
    DataContext="{Binding Mode=Default, XPath=/root/foo[1]/@a}" 
    Content="{Binding}" />  
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号