Peter
Peter

Reputation: 14128

Databinding to XML in a DataTrigger in WPF

In a WPF application, I have correctly bound a DataTemplate to an XML node that looks like:

<answer answer="Tree", correct="false" score="10" />

In my application, I have a TextBlock with the answer in it. At first, I want it invisible, but when the correct attribute in the XML file changes to "true", it must become visible.

My DataTemplate is hooked up correctly, because everything else works. For example, if I change the answer attribute in the XML file (just for testing), it changes in my WPF view. But I'm having troubles with the visibility. This is my XAML:

<TextBlock Text="{Binding XPath=@answer}" Visibility="Hidden">
    <TextBlock.Style>
        <Style>
            <Style.Triggers>
                <DataTrigger Binding="{Binding XPath=@correct}" Value="true">
                    <Setter Property="TextBlock.Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

I'm guessing the Databinding in the DataTrigger isn't working correctly. Anyone have a clue?

Upvotes: 1

Views: 1459

Answers (3)

OptimusPrime
OptimusPrime

Reputation: 61

Sure, it works if you give a specific else case instead of just false. As in my case, it was {x:Null} and value. So when its value to bind is present, it will be true and TextBlock.Visibilty will be set using setters value and when binding path does not have any value inside it, i.e. null in my case, its simply {x:Null} :)

Upvotes: 1

Tim
Tim

Reputation: 1354

I think the issue is that the Visibility property is hard-coded. Try setting the Visibility in the style:

<TextBlock Text="{Binding XPath=@answer}"> 
    <TextBlock.Style> 
        <Style TargetType="{x:Type TextBlock}">
            <Setter Property="Visibility" Value="Hidden"/>
            <Style.Triggers> 
                <DataTrigger Binding="{Binding XPath=@correct}" Value="true"> 
                    <Setter Property="TextBlock.Visibility" Value="Visible" /> 
                </DataTrigger> 
            </Style.Triggers> 
        </Style> 
    </TextBlock.Style> 
</TextBlock> 

Upvotes: 1

Dave
Dave

Reputation: 15016

I have run into the same problem with databound ToggleButtons. Try removing the Visibility="False" and replacing it with another DataTrigger that handles the incorrect case.

Upvotes: 2

Related Questions