在 WPF 中将 Window 的 DataContext 绑定到窗口本身 [英] Binding Window's DataContext to the window itself in WPF

查看:43
本文介绍了在 WPF 中将 Window 的 DataContext 绑定到窗口本身的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个继承自 Window 的简单对话框窗口,我在 XAML 中将其设置为 DataContext,如下所示:

I have a simple dialog window that inherits from Window and I'm setting it's DataContext in XAML like this:

<Window x:Class="MyProject.MyDialog"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        ...>
    <StackPanel>
        <TextBox Text="{Binding SomeText}"/>
        ...
    </StackPanel>
</Window>

这是我显示此对话框的方式:

and here's how I show this dialog:

var dialog = new MyWindow();
MyWindow.SomeText = "some text";

if (dialog.ShowDialog() == true)
    ...

出于某种原因,当窗口被创建并且没有绑定错误时,不会将文本框的初始文本设置为一些文本".

For some reason that doesn't set the initial text of the textbox to "some text" when the window gets created and there's no binding errors.

但是,如果我为 StackPanel 而不是 Window 设置数据上下文:

However, if I set the data context for the StackPanel instead of the Window:

<StackPanel DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}">
    ...
</StackPanel>

一切都按预期进行.

这两者有什么区别?为什么第一种方法不起作用?

What is the difference between these two? Why doesn't the first approach work?

推荐答案

您需要在您的窗口中实现 INotifyPropertyChanged 才能使第一种情况起作用.

You need to implement INotifyPropertyChanged in your window to make first case working.

窗口本身不会被通知其属性(自身)被更改,因此未设置 dc.

Window itself is not notified about its property (self) being changed and hence dc is not set.

这篇关于在 WPF 中将 Window 的 DataContext 绑定到窗口本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆