【发布时间】:2013-08-19 12:18:04
【问题描述】:
我目前在指定或不指定窗口的数据上下文方面遇到一个小问题,以及为什么各种方法之间存在差异。希望你能帮帮我。
让我们从一些代码开始来展示我的问题。这是我的 TestWindow.xaml.cs 背后的代码,没什么特别的,只是一个简单的字符串属性
public partial class TestWindow : Window
{
private string _helloWorld = "Hello World!";
public string HelloWorld
{
get { return _helloWorld; }
set { _helloWorld = value; }
}
public TestWindow()
{
InitializeComponent();
}
}
以下所有 3 个 XAML 布局的代码都是相同的,因此仅在 XAML 中代码后面没有变化。
1.) 给定 ElementName 的数据绑定
<Window x:Class="Ktsw.Conx.ConxClient.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300"
Name="TestWin">
<Grid>
<TextBlock Text="{Binding HelloWorld, ElementName=TestWin}"></TextBlock>
</Grid>
</Window>
2.) 在 Window 上指定 DataContext 的数据绑定
<Window x:Class="Ktsw.Conx.ConxClient.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TextBlock Text="{Binding HelloWorld}"></TextBlock>
</Grid>
</Window>
3.) 既不是 ElementName 也不是指定 DataContext
<Window x:Class="Ktsw.Conx.ConxClient.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300">
<Grid>
<TextBlock Text="{Binding HelloWorld}"></TextBlock>
</Grid>
</Window>
前两种方法效果很好,但为什么第三种方法失败了?
在第一种方法中,我没有指定 DataContext,它会自动工作,在第二种方法中,我没有指定 ElementName,它可以工作,但没有声明其中一个失败。为什么自动获取两者都失败,但单独获取每个都可以正常工作?
【问题讨论】:
-
您能否具体说明在这种情况下“工作正常”和“失败”的含义?它不编译吗?它显示错误吗?它会抛出异常吗?它会使您的计算机崩溃吗?
-
@Default 工作正常 = 显示文本“Hello World!”在文本块中失败 = 不显示文本(保持为空)