简体   繁体   English

在Loaded事件中设置DataContext时无法获取绑定值

[英]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. 如果将用户控件放在窗口中并在该窗口的Loaded事件中设置DataContext,则无法在控件的Loaded事件中检索文本。 Why? 为什么?

If I set the DataContext in MainWindow constructor everything works. 如果我在MainWindow构造函数中设置DataContext,则一切正常。

So is it wrong to set the DataContext in Loaded event? 那么在Loaded事件中设置DataContext是错误的吗?

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. 这里的问题是,当Loaded事件触发时,您只是不能依赖于完成的绑定

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 . 如果将PropertyChangedCallback附加到TextToShow属性,则可以看到在MainWindowLoaded事件中设置DataContext时,它在TestControlLoaded事件之后触发。

Its not required to set the DataContext here, rather than you could go for Binding with RelativeSource .. 不需要在此处设置DataContext ,而是可以与RelativeSource进行Binding

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 DataTemplate 中的按钮如何注册并监听后面代码中按钮的加载事件,但无法访问数据上下文? - How can a button inside of a DataTemplate register and listen to a loaded event of the button in the code behind, but can't access the datacontext? 无法从绑定到LINQ的CheckedListBoxControl获取Value和DisplayMember - Can't get Value and DisplayMember from CheckedListBoxControl bound to LINQ 绑定值更改时,WPF DataTrigger未设置 - WPF DataTrigger not setting when bound value changed WPF。 为 DataContext 属性赋值不会改变绑定属性的值 - WPF. Assigning a value to the DataContext property doesn't change the value of the bound property 在绑定的String上使用时,无法使简单的转换器工作 - Can't get simple converter to work when using on a bound String 绑定到TextBox的DataContext属性在清除TextBox时不会更新 - DataContext property bound to TextBox.Text doesn't update when the TextBox is cleared 无法在页面加载事件中使用Visualtreehelper没有得到任何事件 - Can't use Visualtreehelper in page loaded event don't get any event 设置 DataContext 后的 PropertyChanged 事件为 null - PropertyChanged event null after setting DataContext 修改DataContext时发生WPF事件 - Wpf event when DataContext is modified 从DataContext获取值到MarkupExtension - Get value from DataContext to MarkupExtension
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM