简体   繁体   中英

Can't get bound value when setting DataContext in Loaded event

I have a user control that shows a bindable text. If I put this user control in a window and set the DataContext in Loaded event of that window, I can't retrieve the text in the Loaded event of the control. Why?

If I set the DataContext in MainWindow constructor everything works.

So is it wrong to set the DataContext in Loaded event?

Here is my sample code:

<UserControl x:Class="UserControlBinding.TestControl"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         x:Name="thisControl"
         Loaded="OnLoaded"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">
<Grid>
    <TextBlock Text="{Binding TextToShow, ElementName=thisControl}" />
</Grid>

    public partial class TestControl : UserControl
{
    public string TextToShow
    {
        get { return (string)GetValue(TextToShowProperty); }
        set { SetValue(TextToShowProperty, value); }
    }
    public static readonly DependencyProperty TextToShowProperty =
        DependencyProperty.Register("TextToShow", typeof(string), typeof(TestControl), new PropertyMetadata(null));

    public TestControl()
    {
        InitializeComponent();
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("TestControl.OnLoaded: DataContext=" + DataContext);
        Debug.WriteLine("TestControl.OnLoaded: TextToShow=" + TextToShow);
    }
}


<Window x:Class="UserControlBinding.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlBinding"
    Loaded="OnLoaded"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <local:TestControl TextToShow="{Binding TextToBind}" />
</Grid>

    public partial class MainWindow : Window
{
    public string TextToBind
    {
        get { return (string)GetValue(TextToBindProperty); }
        set { SetValue(TextToBindProperty, value); }
    }
    public static readonly DependencyProperty TextToBindProperty =
        DependencyProperty.Register("TextToBind", typeof(string), typeof(MainWindow), new PropertyMetadata(null));


    public MainWindow()
    {
        InitializeComponent();
        //this.DataContext = this;  // if I do this it works
    }

    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        Debug.WriteLine("+MainWindow.OnLoaded");
        TextToBind = "this is the text to bind";
        this.DataContext = this;
        Debug.WriteLine("-MainWindow.OnLoaded");
    }
}

Debug output is:

+MainWindow.OnLoaded
-MainWindow.OnLoaded
TestControl.OnLoaded: DataContext=UserControlBinding.MainWindow
TestControl.OnLoaded: TextToShow=

The problem here is that you just can't rely on the bindings being completed when the Loaded event fires.

If you attach a PropertyChangedCallback to your TextToShow property you can see that it's fired after the Loaded event of TestControl when you set the DataContext in the Loaded event of your MainWindow .

Its not required to set the DataContext here, rather than you could go for Binding with RelativeSource ..

<TextBlock Text="{Binding TextToShow, RelativeSource="{RelativeSource FindAncestor, AncestorType=UserControl}}" />

<local:TestControl TextToShow="{Binding TextToBind, RelativeSource="{RelativeSource Self}}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM