Thursday, April 21, 2011

Escape from DataContext

I have a window that get its data from another class that is passed as DataContext. But I now also want to do data binding within the window. The window looks as follows:

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <TextBlock Text="{Binding UserName}" />
        <TextBlock x:Name="TestTextBlock">Hello World</TextBlock>
        <TextBlock x:Name="TestTextBlock2" Text="{Binding ElementName=TestTextBlock,Path=Text}" />
    </StackPanel>
</Window>

The binding between the text blocks TestTextBlock and TestTextBlock2 works fine, but only until I change the DataContext-property of the window. How can I bind between those two textblocks so that changing the DataContext will not break the data binding?

Thanks in advance, Stefan

From stackoverflow
  • Try setting the Binding.Mode to OneTime explicitly. That way, TestTextBlock2.Text will only be set once (if that's what you want).

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.